The Dispatch Handler

T
he Dispatch handler, which lives in handlers/dispatch.py, is responsible for invoking the chosen Python script, and getting its output sent back to the browser. To begin, it tries to import the module that was chosen by the Translate handler, using req.modpath. The Python import mechanism is complex beyond belief; if you'd like to explore its inner workings, I suggest reading the C code in the Python interpreter. Or just assume it works and move on.

If an exception occurs during the import, Dispatch sends the text of the exception to the debugging output, and signals Apache to terminate this Apache process. Dispatch does this because a botched import can sometimes leave the Python interpreter in an unstable state. The Python interpreter terminates with the Apache process, and Apache creates a new process and embedded interpreter to take its place. Dispatch finishes handling the exception by sending a 404 Not Found error back to the browser.

If the import succeeded, Dispatch invokes the module's new function, passing it the request object. This function is to return an object which will actually handle the request.

Next, Dispatch examines the URL to determine the type of request it is to handle. There are two types: actions and regular pages. The utils.actions module identifies actions.

If the request is for an action, then Dispatch calls the display object's perform_action() method, which should execute the action and bounce to a new URL.

If the request is for a regular page, then Dispatch calls the display object's check_security() method, which can be used to make sure a page is always in SSL mode, etc. Then it constructs a new CSPage output object and passes it as an argument to the display object's make_page(page) method. Finally, it renders the page into HTML and sends it off to the browser.

Several types of exceptions can occur: a utils.web_exc.WebError is a short message to inform the user of some problem with their request. For example, if a user somehow tries to perform an action for which she does not have permission, the display object raises a WebError with the message "Permission Denied".

A utils.web_exc.SendLiteral exception directs Dispatch to send the given data with the given content-type directly to the browser without any interpretation. This exception can be used, for example, to produce plain-text output, or to dynamically generate images.

Any other type of exception is handled as an error. Dispatch produces 500 Internal Server Error page, and sends the Python traceback to the debugging log.