## 42.9. mod_python

`mod_python` is an Apache module for running Python within the Apache webserver. It's much faster than CGI scripts and generally uses less resources overall. `mod_python` also allows advanced functionality such as maintaining persistent database connections across web requests and access to internal Apache APIs. Information on `mod_python` and distributions are available at http://www.modpython.org.

Apache's basic methodology for handling web requests is to deal with them in phases. There is a phase for each significant element of handling the request, including authentication, content generation, and logging. Apache modules can provide a seperate handler for each phase; `mod_python` simply allows you to write those handlers in Python. This allows complete control over everything Apache does to process a request.

A `mod_python` handler is a function that takes the `Request` object as an argument; a `Request` represents a single web request and contains all the information Apache knows about that request (requested URL, method, headers, and so forth).

Each phase's handler has a specific name that Apache recognizes (and uses in its configuration file): `PythonHandler`, `PythonAuthenHandler`, `PythonLogHandler` and so forth. Most `mod_python` scripts need to implement only the main handler, `PythonHandler`.

`mod_python` finds the appropriate function to call by dropping the leading `Python` from the handler name, and using an all-lowercase function name. Thus, most `mod_python` scripts will look something like this:

>     from mod_python import apache

>     def handler(request):
>         request.content_type = "text/plain"
>         request.send_http_header( )
>         request.write("Hello World!")
>         return apache.OK

This handler simply imports the `apache` API and then responds to every request with a plain text `Hello World!`. It returns `apache.OK` to tell Apache that the request was successful.

For more information on dealing with `mod_python`, read the documentation.

> NOTE: One gotcha: `mod_python`'s way of installing a `mod_python` handler is a little counterintuitive due to the way Apache handlers work. Make sure you understand how `mod_python` finds which module to import.

-- DJPH

Copyright © 2003 O'Reilly & Associates. All rights reserved.