Last active
August 29, 2015 14:04
-
-
Save danielchatfield/ce221624e7a81716abb0 to your computer and use it in GitHub Desktop.
Better decorator
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 myapp import app | |
from werkzeug import BaseResponse | |
from flask import current_app | |
def render_html(template, **defaults): | |
def wrapped(result): | |
variables = defaults.copy() | |
variables.update(result) | |
return render_template(template, **variables) | |
return wrapped | |
def override(f): | |
if current_app.view_functions.get(f.__name__) is not None: | |
f.__name__ = f.__name__ + '_override' | |
return f | |
def view(self, url, renderer=None, *args, **kwargs): | |
super_route = self.route | |
def deco(f): | |
f = override(f) | |
@super_route(url, *args, **kwargs) | |
@wraps(f) | |
def decorated_function(*args, **kwargs): | |
result = f(*args, **kwargs) | |
# catch redirects. | |
if isinstance(result, (app.response_class, | |
BaseResponse)): | |
return result | |
if renderer is None: | |
return result | |
return renderer(result) | |
return f | |
return deco |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment