Prosthetic Conscience

Jason McBrayer's weblog; occasional personal notes and commentary

Mon, 05 Dec 2005

Simpler Apache FCGI Django

Inspired by some tips I saw someplace else, and some fiddling on my own, a simpler Django setup on Apache/mod_fcgi:

Snippet from httpd.conf:

<VirtualHost *:80>
    ServerName mysite.dom
    DocumentRoot /home/httpd/html/mysite/

    AddHandler   fastcgi-script  fcg fcgi fpl fpy
    RewriteEngine on
    RewriteRule ^/media/.*$ - [L]
    RewriteRule ^(/.*)$ /mysite.fcgi$1 [L]

    SetEnv PYTHONPATH /home/httpd/html/mysite
    SuexecUserGroup   myuser mygroup

</VirtualHost>

And what mysite.fcgi looks like:

#!/usr/bin/python
from flup.server.fcgi_fork import WSGIServer
import os
from django.core.handlers.wsgi import WSGIHandler

os.environ[‘DJANGO_SETTINGS_MODULE’] = ‘mysite.settings’

handler = WSGIHandler()
WSGIServer(handler).run() 

You’ll have, of course, to change paths and userids to whatever you need. Features of this setup:

  1. All requests are sent to Django, execpt for paths starting with /media/. This way you do not have to have RewriteRule lines for every application. This method assumes that your entire site except for media/images/etc. is served up with Django (using the flatpages application for everything that’s not an app view, for example).

  2. mysite.fcgi is run as a dynamic FastCGI app. This means it will be started and stopped as necessary by mod_fastcgi process manager, and does not need to be individually added to the Apache config file (indeed, most of the above setup could be done from a .htaccess file assuming the VirtualHost was already set up and configured to accept .htaccess).

  3. If the Apache server is set up with FastCGIWrapper, and Apache is set up correctly for suexec to work with virtual hosts, Django will run as myuser.mygroup, rather than as the Apache user. This is a great comfort in shared hosting environments.

Point 3 could also be accomplished by configuring your django runner script as a FastCGIExternalServer (in httpd.conf) and starting it manually as myuser.mygroup. This is a matter of personal preference. I prefer my way because httpd handles keeping one or more copies of my application running as needed; I don’t have to take further measures to make sure it gets restarted if it dies for some reason (crash, OOM kill, etc). I also like how it makes everything easier to configure (especially in a shared hosting environment, if everything is set up correctly beforehand). However, if you are allergic to Apache’s suexec, you may prefer the alternate method.

[ Posted: 14:15] | [ Category: ] | Permalink | Comments: 2 ]

 


Powered by PyBlosxom