Django/Apache

From Jon's Wiki
Revision as of 02:39, 24 October 2014 by Johnno (talk | contribs) (→‎Example Apache VHost configuration: Apache 2.4)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)

Setting up Django on Apache 2 is relatively straightforward, but with a few kinks noted herewith.

Django Requirements

  • Python >= 2.4
  • Apache 2
  • mod_wsgi - Apache module for Python apps
  • PostgreSQL >= 8.0
  • python-psycopg2 - PostgreSQL client library for Python
  • python-imaging - Python Imaging library
  • memcached and python-memcache (optional but recommended)

Preparation

Django can be installed from the Debian packaged version, and mod_wsgi and psycopg2 can be simply installed using apt-get:

apt-get install python-django libapache2-mod-wsgi python-psycopg2

Check the mod_python Apache module is enabled:

a2enmod wsgi

Example Apache VHost configuration

<VirtualHost *:80>
  ServerName www.clientsite.co.nz

  # static content (for now, but separate domain best)
  AliasMatch /([^/]*\.(gif|png|jpg)) /path/to/myproject'/static/$1
  <Directory /path/to/myproject/static>
    Require all granted
  </Directory>

  WSGIScriptAlias / /path/to/myproject/django.wsgi
</VirtualHost>

Example WSGI file

This would go in the /path/to/myproject/django.wsgi file, as specified in the Apache WSGIScriptAlias directive.

import os
import sys

# You may also need to add the Django path
path = "/path/to/myproject"
if path not in sys.path:
    sys.path.append(path)

os.environ["DJANGO_SETTINGS_MODULE"] = "myproject.settings"
import django.core.handlers.wsgi
application = django.core.handlers.wsgi.WSGIHandler()