← All posts

Installing mod_python for Web Application Development in Python

mod\_python

I decided to try creating a test web application in Python, and the first thing that came to mind was to use mod_python for Apache. After Googling around, I couldn’t find any decent examples, so once I’d figured things out, I decided to write a post about it. Incidentally, strange as it may seem, the most useful example I found was on http://modpython.org/examples/, but I had to rewrite their example through “trial and error” to get anything working. :)

Since I’m running Windows, I’ll use that OS for my examples, but I’ll also show how to do it on FreeBSD.

The mod_python package for Apache lets you run Python scripts and also supports templates using the Python Server Pages mechanism. /2009/python-introduction/

We’ll need:

Installation

Install “ActivePython 2.5.4.4” by following the installer’s instructions; this shouldn’t be difficult. Next, I’m assuming you already have Apache installed, so I’ll move straight on to mod_python.

Run “mod_python-3.3.1.win32-py2.5-Apache2.2.exe”; it will automatically detect where the Python interpreter is located. Follow the instructions.

For FreeBSD, run:


# cd /usr/ports/www/mod_python3/
# make install clean

After installing mod_python, add the following line to “httpd.conf” (after all the “LoadModule” lines):


LoadModule python_module modules/mod_python.so

Also add index.py to the “DirectoryIndex” directive:


<IfModule dir_module>
    DirectoryIndex index.py index.htm index.html
</IfModule>

Configuration

Now let’s add the mod_python initialization directives for a specific host—in my case, “liburg.loc”:


<VirtualHost *:80>
    ServerAdmin youmail@example.com
    DocumentRoot "C:/path/to/liburg.loc/www"
    ServerName liburg.loc

    SetHandler mod_python
    PythonHandler mod_python.publisher
    PythonDebug On

</VirtualHost>

And restart Apache


httpd -k restart

Our First Web Application

Create an index.py file in “C:/path/to/liburg.loc/www” with the following contents:


# мы будем использовать Python Server Pages, поэтому надо его подключить
from mod_python import psp

def index(req):
    # "publisher", который мы повесили в "PythonHandler" вызывает данную ф-ию по умолчанию
    return 'Hello World!'

That’s it—our first web application is ready!

The most important thing is to show you how to get started. From here, you can read up on what PSP is and how to use its templating mechanism; you can look at this example to figure it all out.

Comments are closed. Read the original discussion in Russian →