public
Last active

A comparison of a stupid/simple filter and its implementation as middleware.

  • Download Gist
wsgi2-filter-vs-middleware.py
Python
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65
# 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!

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.