Skip to content

Instantly share code, notes, and snippets.

@podhmo
Created November 8, 2015 01:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save podhmo/a2049d727c47f8550ef9 to your computer and use it in GitHub Desktop.
Save podhmo/a2049d727c47f8550ef9 to your computer and use it in GitHub Desktop.
# -*- coding:utf-8 -*-
from functools import wraps
class MiddlewareApplicator(object):
def __init__(self, fns):
self.middlewares = [middlewarefy(fn) for fn in fns]
def __call__(self, fn):
def call(*args, **kwargs):
context = {}
context["_args"] = args
context["_keys"] = list(kwargs.keys())
context.update(kwargs)
def create_result(context):
args = context["_args"]
kwargs = {k: context[k] for k in context["_keys"]}
return fn(*args, **kwargs)
closure = create_result
for m in reversed(self.middlewares):
closure = m(closure)
return closure(context)
return call
def middlewarefy(fn):
@wraps(fn)
def middleware(closure):
return lambda context: fn(context, closure)
return middleware
if __name__ == "__main__":
# target function
def f(x):
return x * x
def foo_middleware(context, create):
print("foo: before create (context={})".format(context))
context["marker"] = 1
value = create(context)
print("foo: after create (value={}, context={})".format(value, context))
return value
def bar_middleware(context, create):
print("bar: before create (context={})".format(context))
context["marker"] += 1
value = create(context)
print("bar: after create (value={}, context={})".format(value, context))
return value
new_f = MiddlewareApplicator([foo_middleware, bar_middleware])(f)
print(new_f(10))
@podhmo
Copy link
Author

podhmo commented Nov 8, 2015

foo: before create (context={'_keys': [], '_args': (10,)})
bar: before create (context={'_keys': [], 'marker': 1, '_args': (10,)})
bar: after create (value=100, context={'_keys': [], 'marker': 2, '_args': (10,)})
foo: after create (value=100, context={'_keys': [], 'marker': 2, '_args': (10,)})
100

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment