Chapter 15
This concept points toward a functional design for creating web content via a nested
collection of functions that provide enriched input or enriched output or both. With
a little bit of cleverness, we should be able to define a simple, standard interface that
various functions can use. Once we've standardized an interface, we can combine
functions in different ways and add features. We should be able to meet our
functional programming objectives of having succinct and expressive programs that
provide web content.
The WSGI standard
The Web Server Gateway Interface (WSGI) defines a relatively simple, standardized
design pattern for creating a response to a web request. The Python library's wsgiref
package includes a reference implementation of WSGI.
Each WSGI "application" has the same interface:
def some_app(environ, start_response):
return content
The environ is a dictionary that contains all of the arguments of the request
in a single, uniform structure. The headers, the request method, the path, any
attachments for forms or file uploads will all be in the environment. In addition to
this, the OS-level context is also provided along with a few items that are part of
WSGI request handling.
The start_response is a function that must be used to send the status and headers
of a response. The portion of a WSGI server that has final responsibility for building
the response will use a start_response function to send the headers and the status
as well as to build the response text. For some applications, this function might need
to be wrapped with a higher-order function so that additional headers can be added
to the response.
The return value is a sequence of strings or string-like file wrappers that will be
returned to the user agent. If an HTML template tool is used, then the sequence
may have a single item. In some cases, like the Jinja2 templates, the template can
be rendered lazily as a sequence of text chunks, interleaving template filling with
downloading to the user agent.
Due to the way they nest, WSGI applications can also be viewed as a chain. Each
application will either return an error or will hand the request to another application
that will determine the result.