Dynamic Apache interceptors
After looking at the mod_python manual I realized something interesting. mod_python gives you access to the Apache request cycle (e.g. authentication) with something akin to Java servlet filters for Java web servers. mod_python looks like a pretty good way to try out intercepting apache requests before deciding if you want to implement a module using the C API.
Say for example you want to manipulate a file and add a comment to the end saying how long it is you could do it with a request handler:
Another example to add a handler to add header and footer information to a text file is in a brief look at mod_python.from mod_python import apache def handler( request): requestedFile = file(request.filename).read() request.write ( requestedFile ) request.write("\nlength is %s" % len(requestedFile)) return apache.OK
In addition to handlers mod_python also supports input and output filters. Here's a link to the non-trivial example of a gzip filter.
To get Apache to recognize mod_python I enabled .htaccess for my hacks directory in my httpd.conf by using :
<Directory /var/www/coolreason/hacks> # need to pick up .htaccess python directives AllowOverride FileInfo </Directory>
Suppose I only want to apply the handler to .txt files, and ignore .html and others, I can use the following .htaccess file to add the handler:
Where txtlength.py is my handler above. It is dynamic as any changes to txtlength.py are picked up on subsequent Apache requests. UncommentAddHandler mod_python .txt PythonHandler txtlength #PythonHandler mod_python.testhandler PythonDebug On
mod_python.testhandlerif you are having problems and want to test if mod_python is working. There is some good deployment and troubleshooting information available on the mod_python on Pylons Trac.
This technique has really increased my interest in Apache as I can look into the black box with dynamic interceptors.