Apache and mod python

From Django In Production

Jump to: navigation, search

Apache and mod_python is currently the recommended setup for use with Django in production.

Mod_python is an Apache module that embeds the Python interpreter within the server. This gives the ability to have Python code executed in-process by Apache.

The following is a list of required software:

It is currently recommended to use the prefork mpm of Apache. See prefork MPM or worker MPM.

Configuring Apache

To pass requests to Apache on to Django you need to configure which requests you want handled by mod_python. This can be done with the <<Location ... > directive, which binds a set of Apache directives to a particular sub-set of your document root. In the example below any request made to http://myserver.com/mysite/ will be passed to the modpython module in django.core.handlers.

   <Location "/mysite/">
       SetHandler python-program
       PythonHandler django.core.handlers.modpython
       SetEnv DJANGO_SETTINGS_MODULE mysite.settings
       PythonOption django.root /mysite
       PythonPath "['/path/to/project'] + sys.path"
       PythonAutoReload Off
       PythonDebug Off
   </Location>

Line by line this does the following

  • SetHandler python-program - Tells Apache that any requests under this location should be passed to mod_python.
  • PythonHandler django.core.handlers.modpython - This is Django's callable handler that manages mod_python requests.
  • SetEnv DJANGO_SETTINGS_MODULE mysite.settings - Sets the DJANGO_SETTINGS_MODULE environment variable as required by Django. It should point to the settings.py file in the project you want to run.
  • PythonOption django.root /mysite - Passes a value for django.root through to the mod_python handler in Django. In this case Django needs to know that our application is running under /mysite so it matches correctly with URL patterns in the URLConf.
  • PythonPath "['/path/to/project'] + sys.path" - If your projects is not on the machines default PYTHONPATH, you will need to add it using the PythonPath directive.
  • PythonAutoReload Off - By default, mod_python checks the time-stamp of the file and reloads the module if the module's file modification date is later than the last import or reload. Setting this to Off will provide a small performance gain as mod_python will not check the modification date of the module file.
  • PythonDebug Off - PythonDebug should be set to Off on a production machine so as not to expose internal information about your systems to the outside world. Off is the default value for this but it is useful to call this out explicitly so anyone working with this config is aware.

One page setup instructions

Personal tools