Skip to content

Instantly share code, notes, and snippets.

@dhke
Created August 13, 2015 13:39
Show Gist options
  • Save dhke/0d735ae49aed6b70a5b5 to your computer and use it in GitHub Desktop.
Save dhke/0d735ae49aed6b70a5b5 to your computer and use it in GitHub Desktop.
Django automatic decorator
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