http://martin.krogmann.info

Django and CGI

written on Aug. 24, 2011, 6:17 p.m. by Martin Krogmann. Tags: site django cgi
Running the Django Web Framework through CGI

Django is the Web Framework that was used to develop this site. It allows rapid development through Python. The recommend way of running Django applications is to use Apache with mod_wgsi or with mod_python. Those are not always available on web hosting offerings. Therefore an alternative is to run Django through a CGI script when only little traffic has to be handled. Note that this obviously still requires python to be installed on the server. Also, as with all Django distributions it is recommended to run static contents (images, stylesheets, etc.) through the standard Apache http handler.

The Code

The setup consists of two important files. First, you need a cgi script that starts the django wsgi handler with your webpage. Second, you need to have a .htaccess file that tells the apache handler to launch the cgi script to handle pages.

The .htaccess file can look like this:

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

This setup contains the folder site_media that is used to serve static files.

Finally, here is a slightly modified version of my cgi script:


#!/usr/bin/python2.5
# -*- coding: utf-8 -*-
import sys, os import wsgiref.handlers
mypath = os.path.dirname(__file__) # the path to this file on the server
sys.path += [mypath + "/python"] # python is a folder containing the django installation and other python modules sys.path += [mypath + "/mywebpage"] # your django app containing the settings.py


os.environ['DJANGO_SETTINGS_MODULE'] = 'mywebpage.settings' # settings of your django page module
if __name__ == '__main__':
import django.core.handlers.wsgi
# Create a Django application for WSGI.
application = django.core.handlers.wsgi.WSGIHandler()
#print os.environ['LD_LIBRARY_PATH']
wsgiref.handlers.CGIHandler().run(application)

You will need to change 'mywebpage' to your django app name. Also, create a folder python and place a django installation there.

With these settings, the django wsgi handler will find your application and run it.

Fragile CGI scripts

When using cgi scripts, the webserver can be very touchy about your output. Therefore make sure not to have print statements in your django code that result in unspecific error 500 messages that have to be analysed in the server log.

If you still want to use print statements, i.e. if you want to generate a simple output readable in your browser, make sure to use the correct header. A correct header is:

Content-type: text/html\n\n

Notice the trailing '\n\n'. Without these, the server might not accept your content.

Thanks for visiting this site.