[twill] Access to the WSGI environment with wsgi_intercept
ken at redlagoon.net
Mon Jan 7 09:17:16 PST 2008
Well, I think I've succeeded in writing the world's most trivial
middleware. :-) Once I got into this, I realized that I didn't want to
re-issue a request just to dump the environ. Instead, I save off the
environ on every request and access it as needed.
One issue that comes up with this approach is EnvPrinter will have to be the
last middleware in the stack or the environ won't be complete; the test
author will just have to know this requirement. Of course, it's possible
someone might want to dump the environ from the middle of the stack, too, so
maybe this is more of a feature than a bug.
A working example is below. I'm including everything in one script as a
demo, with a namespace hack to show where I'd put things in a finished
If you don't see any design flaws in this, I can work on patches for a
finished product if you'd like.
from twill import wsgi_intercept
# Hack up a psuedo-module for twill_wsgi namespace,
# to show where I'd be putting things eventually.
class X(object): pass
twill.extensions.twill_wsgi = X()
twill.extensions.twill_wsgi.print_environ = print_env
wsgi_intercept.last_request_environ = None
"""Super simple middleware to save off the request's wsgi environ."""
def __init__(self, app):
self.wrapped_app = app
def __call__(self, environ, start_response):
wsgi_intercept.last_request_environ = environ
return self.wrapped_app(environ, start_response)
wsgi_intercept.EnvPrinter = EnvPrinter
# Test it.
def simple_app(environ, start_response):
"""Simplest possible application object"""
status = '200 OK'
response_headers = [('Content-type','text/plain')]
environ['simple_app.myval'] = True
return ['WSGI intercept successful!\n']
""" Test access to the wsgi environment with wsgi_intercept. """
app_fn = wsgi_intercept.EnvPrinter(simple_app)
twill.add_wsgi_intercept('localhost', 80, lambda: app_fn)
val = twill.extensions.twill_wsgi.print_environ('simple_app.myval')
assert val == True, val
# TODO: Implement twill script, python api access. script example:
#>> extend_with twill_wsgi
#>> print_environ foo_name env_variable_to_print
-------------- next part --------------
An HTML attachment was scrubbed...
More information about the twill