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.

  1. import os
  2. class Commenter(object):
  3. def __init__(self, app, storage_dir):
  4. self.app = app
  5. self.storage_dir = storage_dir
  6. if not os.path.exists(storage_dir):
  7. os.makedirs(storage_dir)

When you use this middleware, you’ll use it like:

  1. app = ... make the application ...
  2. app = Commenter(app, storage_dir='./comments')

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 of example.py, and looks like this:

  1. if __name__ == '__main__':
  2. import optparse
  3. parser = optparse.OptionParser(
  4. usage='%prog --port=PORT BASE_DIRECTORY'
  5. )
  6. parser.add_option(
  7. '-p', '--port',
  8. default='8080',
  9. dest='port',
  10. type='int',
  11. help='Port to serve on (default 8080)')
  12. parser.add_option(
  13. '--comment-data',
  14. default='./comments',
  15. dest='comment_data',
  16. help='Place to put comment data into (default ./comments/)')
  17. options, args = parser.parse_args()
  18. if not args:
  19. parser.error('You must give a BASE_DIRECTORY')
  20. base_dir = args[0]
  21. from paste.urlparser import StaticURLParser
  22. app = StaticURLParser(base_dir)
  23. app = Commenter(app, options.comment_data)
  24. from wsgiref.simple_server import make_server
  25. httpd = make_server('localhost', options.port, app)
  26. print 'Serving on http://localhost:%s' % options.port
  27. try:
  28. httpd.serve_forever()
  29. except KeyboardInterrupt:
  30. print '^C'

I won’t explain it here, but basically it takes some options, creates an application that serves static files (StaticURLParser(base_dir)), wraps it with Commenter(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):

  1. from webob import Request
  2. class Commenter(object):
  3. def __init__(self, app, storage_dir):
  4. self.app = app
  5. self.storage_dir = storage_dir
  6. if not os.path.exists(storage_dir):
  7. os.makedirs(storage_dir)
  8. def __call__(self, environ, start_response):
  9. req = Request(environ)
  10. resp = req.get_response(self.app)
  11. return resp(environ, start_response)

This doesn’t modify the response it any way. You could write it like this without WebOb:

  1. class Commenter(object):
  2. ...
  3. def __call__(self, environ, start_response):
  4. return self.app(environ, start_response)

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 becomes http%3A%2F%2Flocalhost%3A8080%2Findex.html).

  1. from cPickle import load, dump
  2. class Commenter(object):
  3. ...
  4. def get_data(self, url):
  5. filename = self.url_filename(url)
  6. if not os.path.exists(filename):
  7. return []
  8. else:
  9. f = open(filename, 'rb')
  10. data = load(f)
  11. f.close()
  12. return data
  13. def save_data(self, url, data):
  14. filename = self.url_filename(url)
  15. f = open(filename, 'wb')
  16. dump(data, f)
  17. f.close()
  18. def url_filename(self, url):
  19. # Double-quoting makes the filename safe
  20. return os.path.join(self.storage_dir, urllib.quote(url, ''))

You can get the full request URL with req.url, so to get the comment data with these methods you do data = 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 but 200), nor do we want to filter responses that aren’t HTML. So we get:

  1. class Commenter(object):
  2. ...
  3. def __call__(self, environ, start_response):
  4. req = Request(environ)
  5. resp = req.get_response(self.app)
  6. if resp.content_type != 'text/html' or resp.status_code != 200:
  7. return resp(environ, start_response)
  8. data = self.get_data(req.url)
  9. ... do stuff with data, update resp ...
  10. return resp(environ, start_response)

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:

  1. import re
  2. class Commenter(object):
  3. ...
  4. _end_body_re = re.compile(r'</body.*?>', re.I|re.S)
  5. def add_to_end(self, html, extra_html):
  6. """
  7. Adds extra_html to the end of the html page (before </body>)
  8. """
  9. match = self._end_body_re.search(html)
  10. if not match:
  11. return html + extra_html
  12. else:
  13. return html[:match.start()] + extra_html + html[match.start():]

And then we’ll use it like:

  1. data = self.get_data(req.url)
  2. body = resp.body
  3. body = self.add_to_end(body, self.format_comments(data))
  4. resp.body = body
  5. return resp(environ, start_response)

We get the body, update it, and put it back in the response. This also updates Content-Length. Then we define:

  1. from webob import html_escape
  2. class Commenter(object):
  3. ...
  4. def format_comments(self, comments):
  5. if not comments:
  6. return ''
  7. text = []
  8. text.append('<hr>')
  9. text.append('<h2><a name="comment-area"></a>Comments (%s):</h2>' % len(comments))
  10. for comment in comments:
  11. text.append('<h3><a href="%s">%s</a> at %s:</h3>' % (
  12. html_escape(comment['homepage']), html_escape(comment['name']),
  13. time.strftime('%c', comment['time'])))
  14. # Susceptible to XSS attacks!:
  15. text.append(comment['comments'])
  16. return ''.join(text)

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 as cgi.escape and just turns & into &amp;, 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 and PATH_INFO. Everything in SCRIPT_NAME has already been parsed, and everything in PATH_INFO has yet to be parsed. That means that the URL without PATH_INFO is the path to the middleware; we can intercept anything else below SCRIPT_NAME but nothing above it. The name for the URL without PATH_INFO is req.application_url. We have to capture it early to make sure it doesn’t change (since the WSGI application we are wrapping may update SCRIPT_NAME and PATH_INFO).

So here’s what this all looks like:

  1. class Commenter(object):
  2. ...
  3. def __call__(self, environ, start_response):
  4. req = Request(environ)
  5. if req.path_info_peek() == '.comments':
  6. return self.process_comment(req)(environ, start_response)
  7. # This is the base path of *this* middleware:
  8. base_url = req.application_url
  9. resp = req.get_response(self.app)
  10. if resp.content_type != 'text/html' or resp.status_code != 200:
  11. # Not an HTML response, we don't want to
  12. # do anything to it
  13. return resp(environ, start_response)
  14. # Make sure the content isn't gzipped:
  15. resp.decode_content()
  16. comments = self.get_data(req.url)
  17. body = resp.body
  18. body = self.add_to_end(body, self.format_comments(comments))
  19. body = self.add_to_end(body, self.submit_form(base_url, req))
  20. resp.body = body
  21. return resp(environ, start_response)

base_url is the path where the middleware is located (if you run the example server, it will be http://localhost:PORT/). We use req.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:

  1. class Commenter(object):
  2. ...
  3. def submit_form(self, base_path, req):
  4. return '''<h2>Leave a comment:</h2>
  5. <form action="%s/.comments" method="POST">
  6. <input type="hidden" name="url" value="%s">
  7. <table width="100%%">
  8. <tr><td>Name:</td>
  9. <td><input type="text" name="name" style="width: 100%%"></td></tr>
  10. <tr><td>URL:</td>
  11. <td><input type="text" name="homepage" style="width: 100%%"></td></tr>
  12. </table>
  13. Comments:<br>
  14. <textarea name="comments" rows=10 style="width: 100%%"></textarea><br>
  15. <input type="submit" value="Submit comment">
  16. </form>
  17. ''' % (base_path, html_escape(req.url))

Nothing too exciting. It submits a form with the keys url (the URL being commented on), name, homepage, and comments.

process_comment

If you look at the method call, what we do is call the method then treat the result as a WSGI application:

  1. return self.process_comment(req)(environ, start_response)

You could write this as:

  1. response = self.process_comment(req)
  2. return response(environ, start_response)

A common pattern in WSGI middleware that doesn’t use WebOb is to just do:

  1. return self.process_comment(environ, start_response)

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:

  1. from webob import exc
  2. from webob import Response
  3. class Commenter(object):
  4. ...
  5. def process_comment(self, req):
  6. try:
  7. url = req.params['url']
  8. name = req.params['name']
  9. homepage = req.params['homepage']
  10. comments = req.params['comments']
  11. except KeyError, e:
  12. resp = exc.HTTPBadRequest('Missing parameter: %s' % e)
  13. return resp
  14. data = self.get_data(url)
  15. data.append(dict(
  16. name=name,
  17. homepage=homepage,
  18. comments=comments,
  19. time=time.gmtime()))
  20. self.save_data(url, data)
  21. resp = exc.HTTPSeeOther(location=url+'#comment-area')
  22. return resp

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 (like HTTPBadRequest and HTTPSeeOther) 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.