Prosthetic Conscience

Jason McBrayer's weblog; occasional personal notes and commentary

Mon, 11 Jun 2007

Installing Django as CGI

When Django was first released, it was only straightforwardly possible to deploy it using mod_python, for which it was designed. However, it also soon included an adapter for WSGI, the Python standard for web application servers to interface with web servers. The WSGI interface was combined with a WSGI-fastcgi gateway called flup to make it possible to host Django applications on FastCGI, and this support eventually became fully integrated with Django. FastCGI is as fast as mod_python, and is somewhat more commonly deployed, especially on commodity shared web-hosting providers.

It is also capable of running the Django app under a different user identity from the web server, either through a suexec wrapper, or by being explicitly started as a server process by another user.

However, while FastCGI is widely deployed, it is not universally deployed, and many hosting providers that support it do so poorly. This article explains how to use the Django WSGI adapter to run Django as a pure CGI application. Performance with this method is terrible, but it might still be suitable for low volume sites on commodity hosting, and especially given adequate caching. It is also a convenient harness for testing, especially for sites to be deployed as FastCGI, and it provides the same separation of privileges from the web server that Fast CGI provides.

Installing a Django project as CGI is very similar to installing it as FastCGI. These instructions presume the use of Apache 2.x. Put this script in your cgi-bin directory. It is derived from the example cgi-wsgi gateway in PEP 333. There’s a similar implementation in Django’s ticket # 2407, but I didn’t know about this when I started writing this note. (I don’t claim any great originality for this method; I just threw together existing components and banged on them until they worked.) Adjust the paths to match where you have installed your project (outside your document root, hopefully!).

Then, you install an htaccess file like this into your DocumentRoot:

AddHandler cgi-script .cgi
RewriteEngine On
RewriteRule ^media - [L]
RewriteRule ^cgi-bin - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*)$ /cgi-bin/django.cgi/$1 [QSA,L]

This will redirect all requests under your DocumentRoot except for cgi-bin, media, and files that actually already exist, to your django cgi script. Again, you will probably have to adjust these paths for your own circumstances, and you may even have to add a RewriteBase directive or something as well.

Now test your admin app. Everything should work correctly, but slowly.

[ Posted: 19:30] | [ Category: ] | Permalink | Comments: 2 ]

 


Powered by PyBlosxom