webob.client
-- Send WSGI requests over HTTPwebob.cookies
-- Cookieswebob.dec
-- WSGIfy decoratorwebob.exc
-- WebOb Exceptionswebob.multidict
-- multi-value dictionary objectwebob.request
-- Requestwebob.response
-- Responsewebob.static
-- Serving static fileswebob
-- Request/Response objects
Comment Example¶
Introduction¶
This is an example of how to write WSGI middleware with WebOb. The specific example adds a simple comment form to HTML web pages; any page served through the middleware that is HTML gets a comment form added to it, and shows any existing comments.
Code¶
The finished code for this is available in docs/comment-example-code/example.py -- you can run that file as a script to try it out.
Instantiating Middleware¶
Middleware of any complexity at all is usually best created as a class with its configuration as arguments to that class.
Every middleware needs an application (
app
) that it wraps. This middleware also needs a location to store the comments; we'll put them all in a single directory.When you use this middleware, you'll use it like:
For our application we'll use a simple static file server that is included with Paste (use
easy_install Paste
to install this). The setup is all at the bottom ofexample.py
, and looks like this:I won't explain it here, but basically it takes some options, creates an application that serves static files (
StaticURLParser(base_dir)
), wraps it withCommenter(app, options.comment_data)
then serves that.The Middleware¶
While we've created the class structure for the middleware, it doesn't actually do anything. Here's a kind of minimal version of the middleware (using WebOb):
This doesn't modify the response it any way. You could write it like this without WebOb:
But it won't be as convenient later. First, lets create a little bit of infrastructure for our middleware. We need to save and load per-url data (the comments themselves). We'll keep them in pickles, where each url has a pickle named after the url (but double-quoted, so
http://localhost:8080/index.html
becomeshttp%3A%2F%2Flocalhost%3A8080%2Findex.html
).You can get the full request URL with
req.url
, so to get the comment data with these methods you dodata = self.get_data(req.url)
.Now we'll update the
__call__
method to filter some responses, and get the comment data for those. We don't want to change responses that were error responses (anything but200
), nor do we want to filter responses that aren't HTML. So we get:So far we're punting on actually adding the comments to the page. We also haven't defined what
data
will hold. Let's say it's a list of dictionaries, where each dictionary looks like{'name': 'John Doe', 'homepage': 'http://blog.johndoe.com', 'comments': 'Great site!'}
.We'll also need a simple method to add stuff to the page. We'll use a regular expression to find the end of the page and put text in:
And then we'll use it like:
We get the body, update it, and put it back in the response. This also updates
Content-Length
. Then we define:We put in a header (with an anchor we'll use later), and a section for each comment. Note that
html_escape
is the same ascgi.escape
and just turns&
into&
, etc.Because we put in some text without quoting it is susceptible to a Cross-Site Scripting attack. Fixing that is beyond the scope of this tutorial; you could quote it or clean it with something like lxml.html.clean.
Accepting Comments¶
All of those pieces display comments, but still no one can actually make comments. To handle this we'll take a little piece of the URL space for our own, everything under
/.comments
, so when someone POSTs there it will add a comment.When the request comes in there are two parts to the path:
SCRIPT_NAME
andPATH_INFO
. Everything inSCRIPT_NAME
has already been parsed, and everything inPATH_INFO
has yet to be parsed. That means that the URL withoutPATH_INFO
is the path to the middleware; we can intercept anything else belowSCRIPT_NAME
but nothing above it. The name for the URL withoutPATH_INFO
isreq.application_url
. We have to capture it early to make sure it doesn't change (since the WSGI application we are wrapping may updateSCRIPT_NAME
andPATH_INFO
).So here's what this all looks like:
base_url
is the path where the middleware is located (if you run the example server, it will behttp://localhost:PORT/
). We usereq.path_info_peek()
to look at the next segment of the URL -- what comes after base_url. If it is.comments
then we handle it internally and don't pass the request on.We also put in a little guard,
resp.decode_content()
in case the application returns a gzipped response.Then we get the data, add the comments, add the form to make new comments, and return the result.
submit_form¶
Here's what the form looks like:
Nothing too exciting. It submits a form with the keys
url
(the URL being commented on),name
,homepage
, andcomments
.process_comment¶
If you look at the method call, what we do is call the method then treat the result as a WSGI application:
You could write this as:
A common pattern in WSGI middleware that doesn't use WebOb is to just do:
But the WebOb style makes it easier to modify the response if you want to; modifying a traditional WSGI response/application output requires changing your logic flow considerably.
Here's the actual processing code:
We either give a Bad Request response (if the form submission is somehow malformed), or a redirect back to the original page.
The classes in
webob.exc
(likeHTTPBadRequest
andHTTPSeeOther
) are Response subclasses that can be used to quickly create responses for these non-200 cases where the response body usually doesn't matter much.Conclusion¶
This shows how to make response modifying middleware, which is probably the most difficult kind of middleware to write with WSGI -- modifying the request is quite simple in comparison, as you simply update
environ
.