Creating Handlers and Working with the API - Python
Python's Apache interpreter is available as an Apache module, mod_python. This module reduces the time it takes to deliver a given page to a client. It is also capable of a great deal more, including interacting with Apache itself in various powerful ways. This article gives you just a taste of what mod_python can do.
I stated earlier in the article that it is possible to change the way Apache does things. This is done through handlers. Apache does its work in steps, or phases. Each of these steps can be performed by a handler. Mod_python registers a handler for each step, which can be populated by Python instructions.
This feature of mod_python is rather interesting, and we can do things with it that are equally as interesting. Let's say we want to change the way text documents are viewed, putting the document inside a pretty layout. We can do this by creating a handler that takes over at the stage where content is gathered and delivered to the user. This might sound a bit confusing, so it's best for me to show you rather than tell you. Create a directory named pyhandler and drop this inside its .htaccess file:
This tells Apache that .txt files are to be handled by mod_python. It then tells mod_python that the file headerfooter.py should be called to handle the .txt files. Create headerfooter.py and add this to it:
That's quite a mouthful, so let's break it down. The first line imports the module apache. This allows us to interact with Apache. We then define a method, handler, that accepts one parameter, request. The request object contains information about (drumroll please) the request.
The next line's function is a bit more obvious. We send out the content type of the page. We then print out a layout using the write method and print the contents of the text file, whose name is contained in the filename method of the request object. We then tell Apache that everything went fine.