Flask website -- 500 Internal Server Error - python

I cannot for the life of me figure of why this flask application I'm trying to launch is not working. I am running it on a $5 Digital Ocean droplet. Here's (hopefully) everything you need to know about it:
Directory layout (contained within /var/www/):
FlaskApp
FlaskApp
__init__.py
static
templates
venv
flaskapp.wsgi
__init__.py:
from flask import Flask
app = Flask(__name__)
#app.route("/")
def hello():
return "yay it worked"
if __name__ == "__main__":
app.run()
flaskapp.wsgi:
#!/usr/bin/python
import sys
import logging
logging.basicConfig(stream=sys.stderr)
sys.path.insert(0,"/var/www/FlaskApp/")
from FlaskApp import app as application
application.secret_key = 'Add your secret key'
FlaskApp.conf (contained in /etc/apache2/sites-availble):
<VirtualHost *:80>
ServerName the.ip.blah.blah
ServerAdmin admin#mywebsite.com
WSGIScriptAlias / /var/www/FlaskApp/flaskapp.wsgi
<Directory /var/www/FlaskApp/FlaskApp/>
Order allow,deny
Allow from all
</Directory>
Alias /static /var/www/FlaskApp/FlaskApp/static
<Directory /var/www/FlaskApp/FlaskApp/static/>
Order allow,deny
Allow from all
</Directory>
ErrorLog ${APACHE_LOG_DIR}/error.log
LogLevel warn
CustomLog ${APACHE_LOG_DIR}/access.log combined
</VirtualHost>
venv was created from calling virtualenv venv within /var/www/FlaskApp/FlaskApp/. I installed flask in venv using pip install flask after entering venv using source venv/bin/activate.
Wsgi has been enabled (a2enmod wsgi). FlaskApp.conf was enabled (a2ensite FlaskApp). And, finally, I restarted apache many times, but to no success (service apache2 restart).
I was following this guide on how to set up a flask application.
Here is a screenshot of what my error looks like:
Any help on getting this to work would be greatly appreciated.
Thanks in advance.
EDIT: I found the problem: ImportError: No module named flask. This is a little strange since I did do pip install flask within the virtualenv. When I just open a python console session in the virtualenv and try import flask I get no error, so not sure what's going on.
Also, how is this application even using venv? I don't see it getting accessed anywhere so how is it even using it? Perhaps this is why i'm getting the ImportError, because I only have flask installed on the virtualenv but it's not being used?

The problem is essentially that you are installing Flask, and possibly other required libraries, in a virtual environment but the python (wsgi interface) is running with the system python which does not have these extra libraries installed.
I have very little recent experience running Python on Apache (I come from an era of mod_python and cgi), but apparently one way to handle this is to use the site package to add the site-packages from your venv to the Python that is executed. This would go in your .wsgi file.
import site
site.addsitedir('/path/to/your/venv/lib/pythonX.X/site-packages')

I think the best way to solve your problem is to add tell your wsgi file about your virtual environment and activate it:
put the following code in your your flaskapp.wsgi
activate_this = '/path/to/env/bin/activate_this.py'
execfile(activate_this, dict(__file__=activate_this))
and restart apache.
hope it will help!
find more here

Related

Trouble hosting Django website in Ubuntu (Error)

I need to host a Django website in Ubuntu 18 (Desktop). I searched the web but couldn't find a well-written tutorial which demonstrates how to do this step by step. After doing some research I came across following procedure but I believe its incomplete.
Library installed
sudo apt-get install python3.6
pip3 install Django
sudo apt-get install apache2
sudo apt-get install libapache2-mod-wsgi
The project named mysite with an app polls and virtual environment mysite_env is located in /var/www with following directory structure
Configured wsgi.py at follows
import os
import sys
from django.core.wsgi import get_wsgi_application
sys.path.append('/var/www/mysite')
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'mysite.settings')
application = get_wsgi_application()
Added following lines in apache2.conf located in etc/apache2/apache2.conf
#ServerName mysite.com
WSGIScriptAlias / /var/www/mysite/mysite/wsgi.py
WSGIPythonHome /var/www/mysite/mysite_env
#WSGIPythonPath /path/to/mysite.com
<Directory /var/www/mysite/mysite>
<Files wsgi.py>
Require all granted
</Files>
</Directory>
If everything setups perfectly then on opening localhost in the browser will let Apache server to open Django app but on the other hand, by doing it Django app doesn't loads.
I am missing lots of things I know, I need to host it and access it on the web. Can anybody tell me what steps I am missing, Any suggestions would be of great help.
References
https://docs.djangoproject.com/en/1.10/howto/deployment/wsgi/modwsgi/y
I followed this simple step to step tutorial which I can recommend. It is for Ubuntu 16.04 but I believe you can simply transfer it to 18.04
https://simpleisbetterthancomplex.com/tutorial/2016/10/14/how-to-deploy-to-digital-ocean.html

Flask app running on apache resulting in 404 error

I'm using mac os x and trying to get the official flask tutorial to work with Apache, but when I attempt to open the site in localhost on my browser it results in a 404: The requested URL / was not found on this server. I followed these directions for configuring mod_wsgi for flask. I've run the app using the built in server with flask so I know the app itself works.
The following is the resulting error in the Apache error log
[negotiation:error] [pid 7563] [client ::1:50509] AH00687: Negotiation: discovered file(s) matching request: /Library/WebServer/Documents/flaskr/flaskr.wsgi (None could be negotiated).
Here is what I have in my flaskr.wsgi file located in /Library/WebServer/Documents/flaskr/flaskr.wsgi
import sys
sys.path.insert(0, '/Library/WebServer/Documents/flaskr')
from flaskr import app as application
I have the following in my httpd.conf file
Listen 80
<VirtualHost *>
ServerName localhost
WSGIDaemonProcess flaskr user=_www group=_www threads=5
WSGIScriptAlias / /Library/WebServer/Documents/flaskr/flaskr.wsgi
<Directory /Library/WebServer/Documents/flaskr>
WSGIProcessGroup flaskr
WSGIApplicationGroup %{GLOBAL}
Require all granted # httpd 2.4 syntax as noted in the guide
</Directory>
</VirtualHost>
LoadModule wsgi_module /usr/local/lib/python3.6/site-packages/mod_wsgi/server/mod_wsgi-py36.cpython-36m-darwin.so
WSGIPythonHome /usr/local/Cellar/python3/3.6.3/Frameworks/Python.framework/Versions/3.6
From terminal when I run sudo apachectl -M it displays wsgi_module (shared). If I comment out the code in my httpd.conf file that I've listed above, the wsgi_module goes away from the enabled modules list, so unless there's something I'm not aware of mod_wsgi seems to be enabled successfully, but as I've mentioned I get a 404 message when trying to view the site.
EDIT
I don't think there's anything wrong with my Apache configuration. I tried this tutorial for getting flask up and running on Apache and it worked. I'll update once I figure out what I did wrong with the "flaskr" app.
Edit - found the problem
Turns out my flaskr.wsgi file was in the wrong directory. It was supposed to be in /Library/WebServer/Documents/flaskr/flaskr/flaskr.wsgi.
The official Flask tutorial I referenced uses the following directory structure
flaskr <----Initially put my `flaskr.wsgi` file in this directory
init.py
flaskr <----Changed to this directory and it worked
flaskr.py
flaskr.db
flaskr.wsgi
Also changed the system path to sys.path.append('/Library/WebServer/Documents/flaskr/flaskr')

404 when trying to deploy basic Flask application with WSGI on Raspberry Pi [duplicate]

This question already has answers here:
Add a prefix to all Flask routes
(15 answers)
Closed 6 years ago.
I've been following the instructions on http://flask.pocoo.org/docs/0.11/deploying/mod_wsgi/ to get my Flask application to be deployed on Apache through WSGI on a Raspberry Pi running Raspbian, but whatever I try, I keep getting a 404-error on the location I've specified. I used the info on various webpages I could find (especially the instructions on http://www.ashokraja.me/post/Serving-a-Python-Flask-Web-Application-via-Apache-Webserver-in-Raspberry-Pi.aspx), but nothing seems to work out.
Logged in as root, I created a directory /var/www/flasktest in which I put two files:
flasktest.py, containing:
#!/usr/bin/python
from flask import Flask
app = Flask(__name__)
#app.route('/')
def hello_world():
return 'Hello World!'
if __name__ == '__main__':
app.run()
and flasktest.wsgi containing:
#!/usr/bin/python
import sys
sys.path.insert(0, '/var/www/flasktest')
from flasktest import app as application
I then did a chmod ugo+x on both files (don't know if that's necessary, though).
I also created /etc/apache2/sites-available/001-flasktest.conf containing
<VirtualHost *:80>
ServerName localhost
WSGIDaemonProcess flasktest threads=5
WSGIScriptAlias /flasktest/ /var/www/flasktest/flasktest.wsgi
<Directory /var/www/flask/flasktest>
WSGIProcessGroup flasktest
WSGIApplicationGroup %{GLOBAL}
Order deny,allow
Allow from all
</Directory>
</VirtualHost>
I executed a2enmod wsgi, a2ensite 001-flasktest.conf and service apache2 reload. Every command was executed as root user.
When I go now go to http://localhost/flasktest I get a 404-error. http://localhost gives me the default Apache-page, so apparently Apache is running correctly. As far as I can see, Apache does not generate any error messages at all.
I really don't know what goes wrong: what makes the 404 come up? Can somebody help me out here? Thanks in advance!
Double-check your WSGIScriptAlias variable- That should be (according to the docs)
WSGIScriptAlias / /var/www/yourapplication/yourapplication.wsgi
Whereas you have
WSGIScriptAlias /yourapplicaiton/ /var/www/yourapplication/yourapplication.wsgi
As Philip Tzou also mentioned, your Directory path may not be correct, either.
Further, sometimes the server name localhost can give you problems. Use 127.0.0.1:80 instead.
It looks like you passed a wrong path to <Directory /> accidentally. Try change /etc/apache2/sites-available/001-flasktest.conf to this:
<Directory /var/www/flasktest>
...
</Directory>
Also you can take a look of apache error log to see what exactly happened.

Apache set-up with Flask and wsgi

I have a small web application that I have built using Flask and python. With the internal server that I used for developing everything runs fine. However now I want to use apache to start using it. But it doesn`t work. Keep in mind that I have never worked with apache or web based stuff before.
I used this guide as my starting point:
http://flask.pocoo.org/docs/deploying/mod_wsgi/
right now I have my application which is in the file called "/rg/server.py" and looks like this:
app=Flask(__name__)
# all app routes...
if __name__ == '__main__':
app.run(
debug=True,
host="127.0.0.1",
port=80
)
than I have a wsgi file as "/rg/wsgi/minerva.wsgi"
import sys
sys.path.insert(0, /rg)
from server import app as minerva
and finally I have an apache config file in "etc/apach2/sites-available/minerva.com":
<VirtualHost *>
ServerName minerva.test
WSGIDaemonProcess minerva threads=10
WSGIScriptAlias / /rg/wsgi/minerva.wsgi
<Directory /rg>
WSGIProcessGroup minerva
WSGIApplicationGroup %{GLOBAL}
Order deny,allow
Allow from all
</Directory>
</VirtualHost>
Then I updated apache with a2ensite minerva.com which succeded. Then I releaded Apache and no errors. However I cannot acces minerva.test in any way...
If I type in apache2ctl -S it does list minerva.test
I have no idea what is going wrong...
system information:
OS: debian 64bit
python 2.7
The WSGI application entry point must be called 'application' for mod_wsgi. You have:
from server import app as minerva
It should be:
from server import app as application
You aren't even getting that far though, else the line:
sys.path.insert(0, /rg)
would give a syntax error.
Going back further, instead of:
<VirtualHost *>
you should have:
<VirtualHost *:80>
and finally, if 'minerva.test' isn't actually a resolvable host, you will not get anywhere.
So fill out your question with the actual URL you are using in the browser and also indicate whether 'minerva.test' is even listed in local hosts file.
The first thing I would check would be to make sure mod_wsgi is installed and loaded by apache. If that's fine, your setup looks pretty similar to mine with a few minor differences:
I had to add WSGISocketPrefix /var/run/wsgi above my VirtualHost definitoin. See here.
I included user and group values on the WSGIDaemonProcess line.

Django deployment problem in Apache/mod_wsgi. ImportError: Could not import settings 'site.settings'

When I'm executing
django-admin.py startproject site
it works.
But if I'm only copying site folder it doesn't work.
Why?
<VirtualHost *:80>
ServerName django.stanislavfeldman.com
# Django settings
WSGIScriptAlias / /var/www/django/wsgi_handler.py
WSGIDaemonProcess django.stanislavfeldman.com maximum-requests=200 stack-size=524288
ErrorLog /var/www/django/error.log
LogLevel warn
</VirtualHost>
wsgi_handler.py:
import os, sys
sys.path.append('/var/www/django')
os.environ['DJANGO_SETTINGS_MODULE'] = 'site.settings'
import django.core.handlers.wsgi
application = django.core.handlers.wsgi.WSGIHandler()
If you have something like this in apache configs:
WSGIScriptAlias /path /base/path/devel/your_project.wsgi
And this inside your_project.wsgi:
sys.path.append('/base/path')
os.environ['DJANGO_SETTINGS_MODULE'] = 'devel.settings'
Then apache will look at /base/path/devel/settings.py. If you move or copy /base/path/devel to /base/path/production you have to edit DJANGO_SETTINGS_MODULE at your_project.wsgi pointing to 'production.settings'.
Ensure you have read:
http://code.google.com/p/modwsgi/wiki/IntegrationWithDjango
and also watch this presentation:
http://code.google.com/p/modwsgi/wiki/WhereToGetHelp?tm=6#Conference_Presentations
Your problem is going to be a sys.path or permissions issue which are both covered by the above.
That you are using 'maximum-requests=200 stack-size=524288' options to WSGIDaemonProcess directive makes me question whether you have referred to the mainstream documentation as basic instructions don't tell you to use them. Instead looks like you have used some arbitrary persons blog post for how to set it up, or relying on some folklore given to you on an IRC channel. :-)
Check your python path to make sure that WSGI can reference it.
I had a problem with a symlink not being followed from the site-packages dir. Double check your apache config and symlinks as well.
This doesn't appear to be the problem in your case, but I ran smack into the same ImportError when I used the WSGIPythonPath directive (instead of the .wsgi file) to set up sys.path. That worked fine until I switched to running WSGI in daemon mode. Once you do that, you have to use the python-path argument to the WSGIDaemonProcess directive instead.

Categories

Resources