Create a gist now

Instantly share code, notes, and snippets.

A comparison of a stupid/simple filter and its implementation as middleware.
# You have a simple application:
def hello(environ):
status = b'200 OK'
headers = [(b'Content-Type', b'text/plain')]
body = b"Hello " + environ['wsgiorg.routing_args'][1]['name'] + b'!'
headers.append((b'Content-Length', len(body).encode('ascii')))
return status, headers, [result]
# Example (really crappy) filter to process GET arguments:
def get_filter(environ):
environ['wsgiorg.routing_args'] = [[], dict()]
args = environ['wsgiorg.routing_args'][1]
for chunk in environ['QUERY_STRING'].split(b'&'):
name, _, value = chunk.partition(b'=')
# need to process value a bit
args[name] = value
# Example usage
HTTPServer(None, 8080, app=hello, ingress=[get_filter]).serve()
# The same as middleware:
def get_middleware(app):
def inner(environ):
environ['wsgiorg.routing_args'] = [[], dict()]
args = environ['wsgiorg.routing_args'][1]
for chunk in environ['QUERY_STRING'].split(b'&'):
name, _, value = chunk.partition(b'=')
# need to process value a bit
args[name] = value
return app(environ)
# Example usage.
HTTPServer(None, 8080, app=get_middleware(hello)).serve()
# The problem with middleware:
HTTPServer(None, 8080, app=\
get_middleware(
post_middleware(
cookie_middleware(
session_middleware(
db_middleware(
hello
)
)
)
)
)
).serve()
# The only callable that -should- be middleware in that stack is db_middleware, as it needs to
# trap exceptions within the application! Middleware stacks are often even deeper than this!
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment