Foundations of Python Network Programming

(WallPaper) #1
Chapter 10 ■ http ServerS

181

Less popular than WebOb for pure WSGI coding but also supported by a loyal fan base is Armin Ronacher’s
Werkzeug library that is also the foundation of his Flask framework (discussed in Chapter 11). Its request and
response objects are immutable, instead of allowing the underlying WSGI environment to be changed. Listing 10-4
shows how its conveniences differ in this case from those of WebOb.


Listing 10-4. WSGI Callable Written with Werkzeug for Returning the Current Time


#!/usr/bin/env python3


Foundations of Python Network Programming, Third Edition


https://github.com/brandon-rhodes/fopnp/blob/m/py3/chapter10/timeapp_werkz.py


A WSGI callable built using Werkzeug.


import time
from werkzeug.wrappers import Request, Response


@Request.application
def app(request):
host = request.host
if ':' in host:
host, port = host.split(':', 1)
if request.method != 'GET':
return Response('501 Not Implemented', status=501)
elif host != '127.0.0.1' or request.path != '/':
return Response('404 Not Found', status=404)
else:
return Response(time.ctime())


Werkzeug has not even made you remember the correct signature for a WSGI callable, instead giving you a
decorator that switches your function to a far simpler calling convention. You receive a Werkzeug Request object
automatically as your only argument and are given the privilege of simply returning a Response object—the library
will handle everything else for you.
The only slight regression from the code written with WebOb is that you have to split hostnames like
127.0.0.1:8000 in two yourself instead of having a convenience method split them out for you. Nevertheless, with
this small difference, the two libraries are doing equivalent work to let you speak about HTTP requests and responses
at a higher level than that exposed by the WSGI convention.
Usually, it will not be worth your time as a developer to operate at this low level instead of using a web
framework. But writing in raw WSGI does come in handy when you want to perform some transform on incoming
HTTP requests before handing them off to your web framework for processing. A straight WSGI application can also
be appropriate if you are writing a custom reverse proxy, or another pure HTTP service, in the Python language.
Raw WSGI callables can be thought to have the same place in Python programming that forward proxies and
reverse proxies have in the HTTP ecosystem at large. They are better for low-level tasks such as filtering, normalizing,
and dispatching requests than they are for doing the positive work of providing resources at specific hostnames and
paths that you want to provide as an HTTP service. For details on how a WSGI callable can modify a request before
handing it off to a further callable, either read the specification or consult the patterns given in either the WebOb or
Werkzeug documentation for writing middleware.

Free download pdf