I keep receiving a 500 Internal Server Error with my Python Flask/CGI program.
I am running it on shared hosting, so I followed this tutorial:
https://medium.com/#dorukgezici/how-to-setup-python-flask-app-on-shared-hosting-without-root-access-e40f95ccc819
This is my main python script: (~/website/mainApp.py)
from flask import Flask
app = Flask(__name__)
#app.route("/")
def home():
return "123 :)"
if __name__ == "__main__":
app.run()
This is my CGI script (~/website/main.cgi)
#!/usr/bin/python
import sys
sys.path.insert(0, "~/.local/lib/python3.7/site-packages")
from wsgiref.handlers import CGIHandler
from mainApp import app
CGIHandler().run(app)
and this is my .htaccess file (~/website/.htaccess):
RewriteEngine On
RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*)$ /main.cgi/$1 [L]
This is basically a file tree of it:
This is the error I am getting:
Internal Server Error
The server encountered an internal error or misconfiguration and was unable to complete your request.
Please contact the server administrator at to inform them of the time this error occurred, and the actions you performed just before this error.
More information about this error may be available in the server error log.
Additionally, a 500 Internal Server Error error was encountered while trying to use an ErrorDocument to handle the request.
Does anyone see where an error may be?
Thanks!
Edit: It now has a weird .pyc file in it. I didn't add it though.?
The contents of your .cgi and .py files look fine.
The main problem is that the permissions on your .cgi file are not correct. Possibly also, the same goes for the website directory -- its permissions are not visible in the file view you posted.
You need execution (and read!) permission on the CGI file, and on any directories leading up to it.
In theory, the following, when run from inside the website directory, should be sufficient:
chmod a+rx . main.cgi
Notice the . to also apply the command to the current (website) directory. This adds read permission and execute permission to the owner, group and others.
If you don't want any permissions applied for the group, then this is sufficient:
chmod uo+rx . main.cgi
As for the .htaccess file, its also valid and would work -- assuming you have mod_rewrite enabled on your server. Check out this post for instructions on enabling that in case you haven't already.
I changed the shebang at the top of the main.cgi file, and it worked.
Before:
#!/usr/bin/python
After:
#!/usr/bin/python3.7
Related
I'm trying to deploy a Flask application on a BlueHost shared hosting server. I have been following this guide. I have made one change, and that is in the .fcgi file. I'm not using flup. This is my .fcgi file (flask.fcgi):
#!/path/to/venv/bin/python
from wsgiref.handlers import CGIHandler
from server import app
CGIHandler().run(app)
I've made the file executable, and when I run ./flask.fcgi from the command line (via SSH) it returns the HTML page for the index route, which is what I expect. But if I navigate to mydomain.com/flask.fcgi I receive a 500 Internal Server error. Checking the server logs I can see this message:
/path/to/venv/bin/python: error while loading shared libraries: libssl.so.3: cannot open shared object file: No such file or directory
I encountered this error before while installing openssl and rectified it by setting the LD_LIBRARY_PATH environment variable to include the path to the location where the libraries were installed. This is my .htaccess file:
# For Flask
PassEnv LD_LIBRARY_PATH
PassEnv REQUEST_METHOD
Options +ExecCGI
AddHandler fcgid-script .fcgi
RewriteEngine On
# For Flask
RewriteCond %{REQUEST_FILENAME} !=/path/to/public_html/flask.fcgi
RewriteRule ^(.*)$ flask.fcgi/$1 [QSA,L]
RewriteOptions inherit
You can see that I try to pass in the LD_LIBRARY_PATH variable, but to no avail, I continue to receive the 500 Internal Server errors, regardless of whether I navigate to mydomain.com/page or to mydomain.com/flask.fcgi directly.
I'm entirely at a loss of where to go from here, any help would be greatly appreciated.
So I figured out what the problem was. I needed to set LD_LIBRARY_PATH and LD_RUN_PATH before compiling openssl and python. I set the paths and then ran ./Configure and make && make install for openssl, and the same for python.
I want to deploy my flask-restx application on a shared hosting. Since I am beginner in deployment, I followed a video tutorial from youtube.
I did step by step by following this tutorial.
For those who do not want to go through the tutorial, I am writing the steps:
I created an application from the Python cPanel
Initial set up in Cpanel
Then I opened terminal and changed my venv and installed flask by "pip install flask"
Project Structure
filas_folder/
├──public
├──tmp
│ └──restart.txt
├──app.py
└──passenger_wsgi.py
app.py looks like
from flask import Flask
app = Flask(__name__)
#app.route("/")
def main_():
return "flask is running"
#app.route("/user")
def main_2():
return "user is running"
if __name__ == "__main__": app.run()
Restart app from cpanel
passenger.py looks like
import imp
import os
import sys
sys.path.insert(0, os.path.dirname(__file__))
wsgi = imp.load_source('wsgi', 'app.py')
application = wsgi.app
when I open www.example.com
flask is running
But when I open www.example.com/user
Internal Server Error
The server encountered an internal error or misconfiguration and was unable to complete your request.
Please contact the server administrator at webmaster#example.com to inform them of the time this error occurred, and the actions you performed just before this error.
More information about this error may be available in the server error log.
Additionally, a 500 Internal Server Error error was encountered while trying to use an ErrorDocument to handle the request.
My system has cloudlinux and uses apache server. This is not the first deployment. Many wordpress and static websites are running on the server.
I opened apache logs at /usr/local/apache/logs/error_log
I get the error "Request exceeded the limit of 10 internal redirects due to probable configuration error. Use 'LimitInternalRecursion' to increase the limit if necessary. Use 'LogLevel debug' to get a backtrace., referer" http://example.com/user"
Add the following to the top of your .htaccess file:
RewriteEngine on
RewriteRule ^http://%{HTTP_HOST}%{REQUEST_URI} [END,NE]
Got this info from: https://stackoverflow.com/a/63971427/10122266
I am trying to load a Flask app in a subdirectory on my domain. Below is my virtual host configuration. the Flask app is kept at /var/www/FlaskApps/Recommender/
Apache's error log keeps saying "Target WSGI script not found or unable to stat: /var/www/FlaskApps/FlaskApp.wsgi" when i try to reach the endpoint /recommender
From online other people said it might be a permission issue, but I'm not sure if it's the case per snapshot below.
Thanks for your help
You have FlaskApps.wsgi in directory, but FlaskApp.wsgi in WSGIScriptAlias directive. So they don't match.
My problem is the following :
I have build an apache server (with python cgi). I have client that try to get a file like http://mysever/file (which is virtual, it does not exist). Depending of the user agent of the client I would like to serve a different file like http://mysever/type1/file or http://mysever/type2/file.
I have tried with ScriptAlias file myscript.py ad I got error 403 Forbidden (my script has been chmoded +x)
I have tried with with Script or Action and I got error 400 Bad Request.
The only thing that works is with Redirect but it seems very ugly.
Can you help me ?
Thank you ! :)
Okay, I have found the solution.
In .htaccess file, in the <Directory> part, I have used :
RewriteEngine On
RewriteBase /
RewriteRule ^file$ myscript.py
Aaaaaaaand it's gone !
I have a test django project that I have been using the django development server for. I want to start using an actual apache server to properly simulate a production environment. I am using Mac OS X.
I have been using this tutorial here, but in the first set of instructions I am getting a 403 from localhost. The browser says I do not have permission to access / on the server.
When I comment out the apache config line from the tutorial, WSGIScriptAlias / /Users/username/Projects/django_books/django_books/django.wsgi I can access localhost.
This is the contents of my django.wsgi file:
import os
import sys
os.environ['DJANGO_SETTINGS_MODULE'] = 'django_books.settings'
import django.core.handlers.wsgi
application = django.core.handlers.wsgi.WSGIHandler()
path = '/Users/username/Projects/django_books/django_books'
if path not in sys.path:
sys.path.append(path)
What is causing the 403 and why can't I see my django application?
EDIT
Directory structure:
django_books
apache (empty directory right now)
random_book
__init__.py
models.py
views.py
django_books
__init__.py
django.wsgi
settings.py
urls.py
views.py
wsgi.py
media
static
css
style.css
manage.py
2ND EDIT
Permissions on all the directories:
/Users/username/Projects/django_books/django_books/django.wsgi
-rw-r--r--
/Users/username/Projects/django_books/django_books
drwxr-xr-x
/Users/username/Projects/django_books/
drwxr-xr-x
/Users/username/Projects/
drwxr-xr-x
/Users/username/
drwxr-xr-x+
/Users/
drwxr-xr-x
According to my small experience I think you must add the following lines "just below the import sys line to place your project on the path" (so juste under "import sys") like it's said in the tutorial you quote. Also, erase the second "django_books" in your path because you want to link to your site not the app in your site ;-) ("mysite" in the tutorial, not mysite/mysite)
import os
import sys
path = '/Users/username/Projects/django_books'
if path not in sys.path:
sys.path.append(path)
os.environ['DJANGO_SETTINGS_MODULE'] = 'django_books.settings'
import django.core.handlers.wsgi
application = django.core.handlers.wsgi.WSGIHandler()
Bye
It's likely an issue related either to your Apache installation, python library, or the filesystem's permissions.
Testing Apache
You don't say it in your question, but I assume from your link you are working with Apache2 and mod_wsgi.
You can test if Apache and mod_wsgi (or your wsgi module) are working properly by placing a dummy wsgi script in the place of django.wsgi . This script (stolen from mod_wsgi's docs) doesn't rely on Django and helps make sure that Apache can read and execute the wsgi script:
# test version of django.wsgi
def application(environ, start_response):
status = '200 OK'
output = 'Hello World!'
response_headers = [('Content-type', 'text/plain'),
('Content-Length', str(len(output)))]
start_response(status, response_headers)
return [output]
And restart apache
sudo service apache2 restart
Go ahead and test the page. Did it work? Great. Undo the changes to the django.wsgi script, restart Apache and test again. If the Django site still doesn't work, we need to keep looking. If the test script didn't work, there may be a problem with your Apache installation. Check apache's error log for more information about what happened. On linux it's commonly at /var/log/apache2/error.log . mod_wsgi could be improperly installed, the script's daemon may not have appropriate permission to the wsgi file.
Correcting permission errors
Apache may not be able to read and execute the wsgi file. Running ls -l in the wsgi file's directory as indicated in other answers will tell you the user and group a file belongs to (and if that user and group can read, write, or execute a given file). It's common for a default installation to have the wsgi permissions like so:
-rw------- 1 www-data www-data 1470 Aug 29 16:00 django.wsgi
If you want to use a different user for the daemon process, you need to make sure that the apache conf file defines WSGIDaemonProccess
WSGIScriptAlias / /Users/username/Projects/django_books/django_books/django.wsgi
WSGIDaemonProcess wsgi_user processes=2 threads=15 display-name=%{GROUP}
WSGIProcessGroup wsgi_group
Testing changes to these files and restarting Apache can help narrow down what's up. Keep checking the Apache log files.
Apache Configuration
Django's tutorial on setting up mod_wsgi is good, but read through mod_wsgi's wiki as well. There are a lot of helpful things to consider in your apache conf file besides WSGIScriptAlias. Make sure there is a tag pointing to the folder with your wsgi file. If there are non-public files (like django project files) in that directory, either use the apache directory (update your apache conf file) or add a tag under the node to keep those other files private. While you're in there, you may notice other things that look wrong, like an improperly configured servername, multiple virtual hosts, or other errors.
Testing Python
If you're using virtualenv (do it), make sure that
1. The WSGIDaemonProcess variable defines the appropriate site-packages and the wsgi script's location in the variable's python-path attribute
2. The daemon has rights to read the site packages in your virtualenv.
3. Your wsgi script properly imports django and your site's settings.
Logging Apache
You can increase the level of logging reported by Apache by adding a few lines to your Apache conf file. This setup gives you very verbose logging that you may want during deployment (make sure to make a log folder):
LogLevel info
ErrorLog /Users/username/Projects/django_books/logs/apache_error.log
CustomLog /Users/username/Projects/django_books/logs/apache_access.log combined
I would suspect that the www-data (or whatever user apache is running as) doesn't have access to /Users/username/Projects/django_books/django_books.
su to that user and try and access that directory and the wsgi file within it.
To print all the relevant permissions:
ls -ld /Users /Users/username /Users/username/Projects /Users/username/Projects/django_books /Users/username/Projects/django_books/django_books /Users/username/Projects/django_books/django_books/django.wsgi
You should also check the apache error logs, they might tell you what is going wrong.