3.2 Your First Handler

Aspen uses handlers to process files such as your index.html. Now we are going to write our own handler.

First, create a directory under aspentut named __ (that's two underscores). This is aspentut's magic directory, and it is where you configure and extend your website. Now create two directories under the magic directory: etc and lib. Under lib, create a python2.x directory, where x corresponds to the minor version of Python you are using. Your directory structure should now look like this:

aspentut
aspentut/__
aspentut/__/etc
aspentut/__/lib/python2.x

In __/lib/python2.x, create a file named handy.py with the following contents:

def handle(environ, start_response):
    start_response('200 OK', [('Content-Type', 'text/plain')])
    return [environ['PATH_TRANSLATED']]

And in __/etc, create a file named handlers.conf with these contents:

fnmatch aspen.rules:fnmatch

[handy:handle]
fnmatch *.asp

What we have done is we have defined a new handler, and wired it up to be used for any request for a file with the extension .asp. So now let's create such a file at aspentut/handled.asp and give it the following contents:

Greetings, program?

Restart Aspen, then hit http://localhost:8080/handled.asp. You should see the filesystem pathname of the file being served.

If you are familiar with the WSGI specification, you will recognize that handy.handle is a WSGI callable. Aspen plugins all speak WSGI. Also notice that the rules for when a certain handler is invoked are themselves extensible. The fnmatch rule comes with Aspen, but you can also write your own.

Aspen is copyright © 2006-2007 by Chad Whitacre and contributors, and is offered under the MIT license.