When we last left off on our framework, we had a simple WSGI app.
def app(environ, respond):
headers = [('Content-type', 'text/plain')]
respond('200 OK', headers)
return ['I have a wife and children!\n']
Not the most dynamic web site in the world. Let’s pass the buck and force some other function to do our hard work.
def app(environ, respond):
headers = [('Content-type', 'text/plain')]
respond('200 OK', headers)
content = content(environ)
return [content]
Note that we’re wallpapering over WSGI’s ability to return iterables by forcing content to return a single string. Iterables are useful, but it’s doubtful you’ll use it because I said so.
While we’re at it, let’s make the status and headers lazy too.
def app(environ, respond):
respond(status(environ), headers(environ))
content = content(environ)
return [content]
This however assumes that getting the status, headers, the content are three independent processes, which isn’t the case. There’s usually a duplication of effort when approached this way especially since you’re most likely going to do some serious work massaging the environ.
Pimp my response.
It looks like we need a cooler data model. Fortunately, Python’s classes have an extremely flexible one where you have attributes, magic methods, constructors, inheritance, and balloons, balloons for small children.
def app(environ, respond):
response = Response(environ)
respond(response.status(), response.headers())
return [response.content()]
It’s not immediately obvious, but environ as a dictionary of strings to strings is usually too flat to be of any real benefit. A better architecture would be a separate phase for parsing the environ into neat little variables.
def app(environ, respond):
request = Request(environ)
response = Response(request)
respond(response.status(), response.headers())
return [response.content()]
Now all that remains is to plug holes and build adventures.