3.3 Your First Handler

Aspen uses handlers to process your index.html and foo.py files. 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):
    return environ['aspen.fp'].name

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. That's because environ['aspen.fp'] points to an open file object of that file.

If you are familiar with the WSGI specification, you will recognize that handy.handle is very nearly a WSGI callable. Aspen plugins all speak a slight superset of 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 Zeta software. It is copyright © 2006 by Chad Whitacre, and is offered free of charge, warranty, and restrictions.