Created

Embed URL

HTTPS clone URL

SSH clone URL

You can clone with HTTPS or SSH.

Download Gist

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

View wsgi2-filter-vs-middleware.py
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!
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Something went wrong with that request. Please try again.