Use Python like PHP (in public_html with wsgi)
You want to set up a LAMP (Linux, Apache, MySQL, Python) environment at home for testing purposes.
In addition, we want to create a
public_html directory in our HOME directory and we want to put our Python web scripts in there.
I suppose Apache2 is installed and works correctly. If you visit http://localhost/, you should see the text “It works!”.
Now, create the directory
~/public_html and put in this folder a basic
index.html file with some greetings context (like “<h1>hello from index.html<h1>”). Enable the user directories and restart the web server:
$ sudo a2enmod userdir $ sudo service apache2 restart
http://localhost/~%5Busername%5D/index.html. You should see the greetings.
Install and enable WSGI in user directories
Create the file
def application(environ, start_response): """"Simplest possible application object""" status = '200 OK' response_headers = [('Content-type', 'text/plain')] start_response(status, response_headers) return ['Hello, World!\n']
Point your browser to this file. It’s very likely that your browser will try to download this file, which means that WSGI is not yet configured.
Install the WSGI module and enable it in Apache2:
$ sudo apt-get install libapache2-mod-wsgi $ sudo a2enmod wsgi
/etc/apache2/apache2.conf and add this line to the end:
For each wsgi user on the system, add the following lines to the end of
WSGIDaemonProcess [user name] user=[user name] home=/home/[user name]/public_html <Directory /home/[user name]/public_html> WSGIProcessGroup [user name] </Directory>
Add the following lines to
/etc/apache2/sites-available/default above the closing
<Directory /home/*/public_html> Options Indexes FollowSymLinks MultiViews ExecCGI AddHandler wsgi-script .wsgi Order allow,deny Allow from all </Directory>
Restart Apache2 with “
sudo service apache2 restart” and point your browser to
hello.wsgi. It should work fine.
Get Flask work with Apache2 + mod_wsgi
Put in the ~/public_html/hello2.wsgi file the following:
from flask import Flask app = Flask(__name__) application = app # The trick is HERE! Add this extra line! @app.route("/") def hello(): return "Hello Flask!" if __name__ == "__main__": app.run()