Created
August 18, 2011 22:43
-
-
Save mattupstate/1155466 to your computer and use it in GitHub Desktop.
Simple way of implementing before and after filters in a web.py app
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def before_filter(*args, **kwargs): | |
print "before" | |
def after_filter(*args, **kwargs): | |
print "after" | |
class Controller(object) | |
@RequestFilter(before=[before_filter], after=[after_filter]) | |
def GET(self): | |
return "Hello!" | |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from functools import update_wrapper | |
class RequestFilter(object): | |
def __init__(self, before=[], after=[], **kwargs): | |
self.before = before | |
self.after = after | |
def __call__(self, function): | |
def wrapper(request, *args, **kwargs): | |
for b in self.before: | |
b(*args, **kwargs) | |
result = function(request, *args, **kwargs) | |
for a in self.after: | |
a(*args, **kwargs) | |
return result | |
update_wrapper(wrapper, function) | |
return wrapper |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment