Subsections

2.1 httpy -- Smooth out WSGI's worst warts

The request side of WSGI--the "commons" of the environ mapping--is quite nice. It honors the tradition of CGI, and it's just a mapping. Simple.

The response-side API is a little stiffer, because WSGI has to support edge cases like serving large files, complex exception handling, and HTTP/1.1 features. This results in warts like start_response, and the requirement that apps return an iterable. The intention in PEP 333 is that these warts be smoothed over at other layers; this is such a layer.

httpy provides the following classes:

class Responder( app)
Constructs a new Responder object. app is an extended WSGI application: it may alternately return a string, or return or raise a Response object.

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). body must be a string. headers may be a dictionary or a list of 2-tuples. body is second rather than headers because one more often wants to specify a body without headers than vice versa.


2.1.1 Responder Objects

Instances of httpy.Responder are callables that speak plain WSGI on the server side, but they also accept strings and Response objects from the application side. When a Responder receives a Response object, that becomes the WSGI endpoint. When a Responder receives a string, it creates a Response object with the string as the body, and the Content-Type: set to text/html. This implicit Response then becomes the endpoint.


2.1.2 Response Objects

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

code
The HTTP code as an integer.

body
The message body as a string.

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 a one-item list containing body.


2.1.3 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.
>>>
>>> import httpy
>>> app = lambda env, start: "Greetings, program!"
>>> app = httpy.Responder(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
lib537 is Zeta software. It is copyright © 2006 by Chad Whitacre, and is offered free of charge, warranty, and restrictions.