(Yet Another) Deploying Django with CherryPy Script

  2009-02-18


Recently I deployed a Django project on an OSX server. I foolishly thought this would be as easy as on Linux until I ran into the mess that is _x8664 Apache + mod_wsgi* + Django + psycopg2 + i386 PostgreSQL. After wasting far too much time googling and recompiling various bits trying to get everything happy, I followed Eric Florenzano’s post on deploying Django using CherryPy‘s** wsgiserver.

Here’s my lightly modified version of Eric’s script:

import wsgiserver
import sys
import os
import django.core.handlers.wsgi

if __name__ == "__main__":
    # Setup paths - a bit hackish, but works for me.
    # Assumes an absolute path is stored in <project>.local_settings.ROOT
    sys.path.append(os.path.realpath(os.path.dirname(__file__)))
    from foo.local_settings import ROOT
    sys.path.append(ROOT)

    # Startup Django
    os.environ['DJANGO_SETTINGS_MODULE'] = 'foo.settings'
    server = wsgiserver.CherryPyWSGIServer(
        ('0.0.0.0', 8888),  # Use '127.0.0.1' to only bind to the localhost
        django.core.handlers.wsgi.WSGIHandler()
    )
    try:
        server.start()
    except KeyboardInterrupt:
        print 'Stopping'
        server.stop()

I also went with the latest stable version of CherryPy’s wsgiserver instead of checking out trunk like Eric’s post suggested.

Then I just enabled mod_proxy in Apache and setup the following VirtualHost:

<Proxy *>
    Order allow,deny
    Allow from all
</Proxy>
<Location "/">
    ProxyPass http://127.0.0.1:8888/
    ProxyPassReverse http://127.0.0.1:8888/
</Location>

If you’re cool you’ll write some sort of system specific script to launch your web app on boot. In a pinch, you can always use a crontab:

@reboot /usr/bin/python /path/to/app.py &

YMMV 😉


* To mod_wsgi’s credit, it took about 10 seconds to compile, generated a Universal binary, and in general Just Worked.

** I’m already a CherryPy fan thanks to dowski, so it wasn’t a hard decision.