How to Deploy Python Web App With Apache’s Mod_wsgi

|

For quite a while I couldn’t figure out how to deploy Python web apps. But with patience and tinkering, I slowly figured it out.

Here were my steps:

1. Setup Domain

I created an A record for python.davidxia.com in my DNS records pointing to the IP of the server on which I developed.

2. Setup Apache VirtualHost

I put this in /etc/apache2/sites-available/davidxia (using Ubuntu 10.04):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
<VirtualHost *:80>
    ServerName python.davidxia.com

    WSGIDaemonProcess myapp user=www-data group=www-data processes=1 threads=5
    WSGIScriptAlias / /path/to/myapp/myapp.wsgi
    WSGIScriptReloading On

    <Directory /path/to/myapp>
        WSGIProcessGroup myapp
        WSGIApplicationGroup %{GLOBAL}
        Order deny,allow
        Allow from all
    </Directory>
</VirtualHost>

The WSGIScriptReloading On makes mod_wsgi reload all the daemon processes whenever something changes the .wsgi file. This makes it convenient to make code changes and run:

touch myapp.wsgi

3. Install Python Framework

To keep things simple, I’ll use Flask, a micro web framework for Python, as an example of how to get a web app up and running.

pip install Flask

4. Create Flask Hello World

1
2
3
4
5
6
7
8
9
from flask import Flask
app = Flask(__name__)

@app.route("/")
def hello():
    return "Hello World!"

if __name__ == "__main__":
    app.run()

5. Fix mod_wsgi Threading Errors (optional)

I noticed dozens of these errors in my Apache error log:

[error] Exception KeyError: KeyError(-1219327344,) in  ignored

They are apparently harmless, but I wanted to get rid of them since they’re annoying to see. I fixed it by updating mod_wsgi to version 3.3. This wasn’t in Ubuntu’s repository, so I downloaded version 3.3, stopped Apache, installed from source, and restarted Apache.

6. Test

I pointed my browser at python.davidxia.com and got “Hello World!”