blog stats
seamusc.com

How to get Django working on digiweb.ie using django.cgi

Published on June 11, 2007

I just thought I'd post exactly what I did to get django running on digiweb.ie shared hosting

First I downloaded and extracted Django version 0.96 to ~/Django-0.96

All requests will then be forwarded through the django.cgi script which I have saved as cgi-bin/dj

.htaccess

RewriteEngine on
RewriteRule ^cgi-bin/ - [L]
RewriteRule ^media/ - [L]
RewriteRule ^(.*)(/)$ cgi-bin/dj/$1/
RewriteRule ^$ cgi-bin/dj/home/

This is the script which will process all requests.

cgi-bin/dj

#!/usr/bin/python
# encoding: utf-8
"""
django.cgi

A simple cgi script which uses the django WSGI to serve requests.

Code copy/pasted from PEP-0333 and then tweaked to serve django.
http://www.python.org/dev/peps/pep-0333/#the-server-gateway-side

This script assumes django is on your sys.path, and that your site code is at
/home/mycode/mysite. Copy this script into your cgi-bin directory (or do
whatever you need to to make a cgi script executable on your system), and then
update the paths at the bottom of this file to suit your site.

This is probably the slowest way to serve django pages, as the python
interpreter, the django code-base and your site code has to be loaded every
time a request is served. FCGI and mod_python solve this problem, use them if
you can.

In order to speed things up it may be worth experimenting with running
uncompressed zips on the sys.path for django and the site code, as this can be
(theorectically) faster. See PEP-0273 (specifically Benchmarks).
http://www.python.org/dev/peps/pep-0273/

Make sure all python files are compiled in your code base. See
http://docs.python.org/lib/module-compileall.html

"""

import os, sys 
# insert a sys.path.append("whatever") in here if django is not
# on your sys.path.
sys.path.append("/hsphere/local/home/seamusc/Django-0.96")
sys.path.append("/hsphere/local/home/seamusc")
import django.core.handlers.wsgi

def run_with_cgi(application):

    environ                      = dict(os.environ.items())
    environ['wsgi.input']        = sys.stdin
    environ['wsgi.errors']       = sys.stderr
    environ['wsgi.version']      = (1,0)
    environ['wsgi.multithread']  = False
    environ['wsgi.multiprocess'] = True
    environ['wsgi.run_once']     = True

    if environ.get('HTTPS','off') in ('on','1'):
        environ['wsgi.url_scheme'] = 'https'
    else:
        environ['wsgi.url_scheme'] = 'http'

    headers_set  = []
    headers_sent = []

    def write(data):
        if not headers_set:
             raise AssertionError("write() before start_response()")

        elif not headers_sent:
             # Before the first output, send the stored headers
             status, response_headers = headers_sent[:] = headers_set
             sys.stdout.write('Status: %s\r\n' % status)
             for header in response_headers:
                 sys.stdout.write('%s: %s\r\n' % header)
             sys.stdout.write('\r\n')

        sys.stdout.write(data)
        sys.stdout.flush()

    def start_response(status,response_headers,exc_info=None):
        if exc_info:
            try:
                if headers_sent:
                    # Re-raise original exception if headers sent
                    raise exc_info[0], exc_info[1], exc_info[2]
            finally:
                exc_info = None     # avoid dangling circular ref
        elif headers_set:
            raise AssertionError("Headers already set!")

        headers_set[:] = [status,response_headers]
        return write

    result = application(environ, start_response)
    try:
        for data in result:
            if data:    # don't send headers until body appears
                write(data)
        if not headers_sent:
            write('')   # send headers now if body was empty
    finally:
        if hasattr(result,'close'):
            result.close()

# Change this to the directory above your site code.
sys.path.append("/hsphere/local/home/seamusc")
os.chdir("/hsphere/local/home/seamusc")
# Change mysite to the name of your site package
os.environ['DJANGO_SETTINGS_MODULE'] = 'webapp.settings'
run_with_cgi(django.core.handlers.wsgi.WSGIHandler())

Comments

stupid
June 19, 2007 at 4:42 a.m.

uhm? where doe sthe .htaccess go what folder? how uhm can i get my site to load on mysite.com/django folder

seamus
June 19, 2007 at 9:10 a.m.

.htaccess file can go anywhere inside your webroot folder and affects all subfolders.
You shoud read up on .htaccess
To have your django site available at /django/ change


RewriteRule ^(.*)(/)$ cgi-bin/dj/$1/

to


RewriteRule ^django/(.*)(/)$ cgi-bin/dj/$1/

and leave out the last line

Oin
August 25, 2007 at 9 a.m.

I'm trying to use this in a subdirectory, but something goes wrong.


the subdirectory where everything should be is /oin on the webserver.


So my .htaccess looks like this:


RewriteEngine on
RewriteRule ^(.*)(/)$ dj/$1/
and is located in /oin


now i changed syspath.append to look like this:


sys.path.append("/home/example/public_html/oin/django")


because i renamed the Django-0.96 to django and put it in /oin


I don't understand why the next line after this one should look like this (judjing by your config):


sys.path.append("/home/example/public_html/oin/")


doesn't this override the previous line?


at the bottom of /oin/dj i have:


sys.path.append("/home/example/public_html/oin")
os.chdir("/home/example/public_html/oin")


os.environ['DJANGO_SETTINGS_MODULE'] = 'mysite.settings'


the directory of my django project is /oin/mysite


So now when i visit example.com/oin/mysite/
or example.com/oin/dj
or example.com/oin/dj/mysite


there's nothing there but
a blank page.


so what am i doing wrong?


and btw, please make this comment box wider.

drsanchez
October 27, 2007 at 12:24 a.m.

Would you be willing to post a tree of your directory structure, including where your django projects and apps are? I'm getting hung up on something and I suspect it's one little thing pointing to the wrong directory.


Thanks.

Marko
April 10, 2008 at 8:39 a.m.

It would be great if you could post that directory tree please?

Marko
April 10, 2008 at 10:25 a.m.

I have downloaded django.96 to the root dir.


I created the .htaccess file just as above.


I created the cgi-bin/dj file and gave it permissions. I modified where appropriote.
/hsphere/local/home/thisiscool/Django-0.96
/hsphere/local/home/thisiscool/
thisiscool.settings


It is not working (still showing the index.html page. - I dont know what i am missing - please please help.

Marko
April 10, 2008 at 10:32 a.m.

My exact problem may be shown here - when i try to access cgi-bin/dj it says:


Error 500: Internal Server Error


The server encountered an unexpected condition which prevented it from fulfilling the request.


The problem is on the server side, not with your browser or the address. Most probably, a certain service (e.g., Tomcat engine) is down. Please contact your webmaster.


Please please help

habnabit
April 30, 2008 at 3:22 p.m.

You're reraising the exception incorrectly. "raise" by itself will reraise the current exception.