3.3.4 Writing a Responder

In httpy, a responder is simply an object with a respond callable. For example, a responder can be a module with a respond function, or a class instance with a respond method. Responders have two optional data attributes, which, if not present, will be added by whatever coupler is in use. For responders that are classes, this API addition takes place prior to instantiation, so the information is available to the constructor.

class IResponder

respond( request)
Responds to a single HTTP request. request is a Request object. The transaction is ended by either returning or raising a Response object, which is converted to an HTTP Response message and written out to the wire. All other Exceptions result in a 500 Internal Server Error response.

stop( )
This optional method is called when the application terminates normally.

The location of the responder on the local filesystem.

The location of the responder on the network.

Responders are validated using Zope's interface machinery. Your responder may provide this interface without explicitly declaring so. If a responder does not have a respond callable, or if respond does not accept exactly one argument, then an Exception is raised.

Responders must be able to respond to multiple (non-concurrent) requests. An Example

Here is an example showing the general feel of a responder. This example assumes a logic module with API for getting and setting data based on a URI path and a POST body. The suggestion here is that these might return a commonly formatted data structure, which would then be used to populate a common template. Notice the authorization check before setting data.

import auth
import logic
import templating

from httpy import Response

def respond(request):

    if request.method == 'GET':
        result = logic.get_data(request.path)
    elif request.method == 'POST':
        if not auth.check(request):
            raise Response(403)
        result = logic.set_data(request.path, request.raw_body)
        raise Response(501)

    template = templating.get_template(request.path)
    body = template.render(result)
    return Response(200, body)

This is a contrived example, basically following the popular Model-View-Controller pattern: the auth and logic modules are the model, the templating module provides the view, and the responder is the controller. However, this pattern is not enforced in any way, and the bottom line is that you've got all of Python to play with in writing your responders.

httpy is Zeta software. It is copyright © 2006 by Chad Whitacre, and is offered free of charge, warranty, and restrictions.