[twill] Access to the WSGI environment with wsgi_intercept
Ken Kuhlman
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
product.
If you don't see any design flaws in this, I can work on patches for a
finished product if you'd like.
thanks,
-Ken
import twill
import twill.extensions
try:
import wsgi_intercept
except ImportError:
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()
def print_env(env_var):
return wsgi_intercept.last_request_environ[env_var]
twill.extensions.twill_wsgi.print_environ = print_env
wsgi_intercept.last_request_environ = None
class EnvPrinter:
"""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):
global last_request_environ
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
start_response(status, response_headers)
return ['WSGI intercept successful!\n']
def test_print_environ():
""" 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)
print 'go'
twill.commands.go('http://localhost:80/')
print 'print_environ'
val = twill.extensions.twill_wsgi.print_environ('simple_app.myval')
assert val == True, val
print 'remove'
twill.remove_wsgi_intercept('localhost', 80)
# 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...
URL: http://lists.idyll.org/pipermail/twill/attachments/20080107/c2338e85/attachment.htm
More information about the twill
mailing list