Django on Apache on Snow Leopard, Part 1: mod_wsgi

So recently I decided to stop running mamp and use the default installation of Apache on Snow Leopard (basically, just turning on Apache using commands in Terminal).

Now that I have Apache running, I’d like to get Django running.

This isn’t as easy.

There are several methods to try…I tried using Macports but the method below was easier.

The recommended way to run Django on Apache is to use a module called mod_wsgi, which is an open-source module that gets Python working on Apache.

Check your version of Apache. Open Terminal and type

httpd -v

Then press enter.

You should see

Server version: Apache/2.2.17 (Unix)

Check your version of Python.

python

You should see:

Python 2.6.6

Note: If you’ve downloaded a later version of Python (say, 2.7 or 3) it won’t work with the mod_wsgi install method here!

Next, go to the mod_wsgi site and download the Mac binary.

Rename the downloaded file to

mod_wsgi.so

And put it in the folder /usr/libexec/apache2. The folder /usr/ is at the very top of your drive, above the /Users/ folder. If you can’t see it, you can turn on hidden files in the Finder.

Then, make a folder called ‘codetest’ in your username folder.

cd ~
mkdir codetest

Open your httpd.conf file.

cd /etc/apache2/
sudo nano httpd.conf
Password: (enter your Mac password)

Pressing Control+V will take you down the file to where it starts to read…

LoadModule....

Add this near the bottom:

LoadModule wsgi_module     libexec/apache2/mod_wsgi.so

Then, assuming you have your httpd-vhosts.conf file enabled

cd /etc/apache2/extra/
sudo nano httpd-vhosts.conf
Password: (enter your Mac password and hit enter)

Press Control+V to take you to the bottom of the file, then enter:

WSGIScriptAlias /myapp /Users/yourusername/codetest/test.py

<Directory /Users/yourusername/codetest/>
Order allow,deny
Allow from all
</Directory>

Change ‘yourusername’ to the user name of your computer.

Switch back into the folder named ‘codetest’.

cd ~
cd codetest

Create a new text file, called test.py

sudo nano test.py
password: (Enter your Mac password and hit enter)

This will open up the nano editor. Paste the following:

def application(environ, start_response):
    status = '200 OK'
    output = 'Hello World!'

    response_headers = [('Content-type', 'text/plain'),
                        ('Content-Length', str(len(output)))]
    start_response(status, response_headers)

    return [output]

Then press Control+X to exit, press Y to save and hit enter.

Going to http://localhost/myapp should show the following:

Hello, world!

If you get an internal server error, make sure you don’t have any extra spaces before the ‘def application’ line in your test.py file.