-
-
Save johndiego/7b40ee9bb1cc11e3b582bc672ae300a7 to your computer and use it in GitHub Desktop.
Flask MethodView decorators for individual request methods
This file contains hidden or 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 flask.views import MethodView | |
class MethodView(MethodView): | |
_decorators = {} | |
def dispatch_request(self, *args, **kwargs): | |
"""Derived MethodView dispatch to allow for decorators to be | |
applied to specific individual request methods - in addition | |
to the standard decorator assignment. | |
Example decorator use: | |
decorators = [user_required] # applies to all methods | |
_decorators = { | |
'post': [admin_required, format_results] | |
} | |
""" | |
view = super(MethodView, self).dispatch_request | |
decorators = self._decorators.get(request.method.lower()) | |
if decorators: | |
for decorator in decorators: | |
view = decorator(view) | |
return view(*args, **kwargs) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment