Created
August 13, 2015 13:39
-
-
Save dhke/0d735ae49aed6b70a5b5 to your computer and use it in GitHub Desktop.
Django automatic decorator
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
def decorator_on_class(decorator): | |
""" | |
Apply the supplied view decorator to the specified | |
class. | |
""" | |
def decorate_class(cls): | |
dispatch = cls.dispatch | |
@wraps(dispatch) | |
@method_decorator(decorator) | |
def wrapper(self, *args, **kwargs): | |
return dispatch(self, *args, **kwargs) | |
cls.dispatch = wrapper | |
return cls | |
return decorate_class | |
def auto_decorator(decorator): | |
""" | |
A meta-decorator that works for both class-based | |
as well as method based views. | |
For class-based views, only the dispatch() | |
method is wrapped (using decorator_on_class()) | |
Uses inspect.isclass() to determine if the decorated | |
object is a class. | |
""" | |
def wrapper(cls_or_method): | |
if inspect.isclass(cls_or_method): | |
return decorator_on_class(decorator)(cls_or_method) | |
else: | |
return decorator(cls_or_method) | |
return wrapper |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment