Subsections

5.2.1 raised

The aspen.middleware.raised module provides for ending WSGI requests by raising a Response object that is caught by a middleware:

class Response( [code] [, body] [, headers])
Constructs a new Response object. If given, code must be an integer; the default is 200 (see the HTTP spec for other values that will be meaningful to most HTTP clients). headers may be a dictionary or a list of 2-tuples. body may be a string or other iterable.

middleware( next)
WSGI middleware; next is the next WSGI callable on the stack. This middleware catches any Response objects raised by next and calls them (they are themselves WSGI callables) to produce the response.

5.2.1.1 Response Objects

Instances of aspen.middleware.raised.Response are WSGI applications, with the following data attributes. Note that values are only validated in the constructor, so it is possible to raise a malformed Response by setting instance attributes post-instantiation.

code
The HTTP code as an integer.

body
The message body as a string or other iterable.

headers
The message headers as an instance of the standard library's email.Message.Message.

When called, Response instances call start_response with adaptations of code and headers, and return body, or a one-item list containing body if body is a string.

5.2.1.2 Example

Here is an example:

Python 2.5 (r25:52005, Sep 25 2006, 21:37:36)
[GCC 3.4.4 [FreeBSD] 20050518] on freebsd6
Type "help", "copyright", "credits" or "license" for more information.
>>>
>>> from aspen import raised
>>> def app(env, start):
>>>     raise raised.Response(200, "Greetings, program!")
>>> app = raised.middleware(app)
>>>
>>> from wsgiref.simple_server import make_server
>>> server = make_server('', 8080, app)
>>> server.serve_forever() # now hit http://localhost:8080/
>>>
192.168.1.100 - - [09/Nov/2006 23:52:45] "GET / HTTP/1.1" 200 19
Aspen is copyright © 2006-2007 by Chad Whitacre and contributors, and is offered under the MIT license.