#13879: method_decorator doesn't supports decorators with arguments
---------------------------+------------------------------------------------
Reporter: marinho | Owner: nobody
Status: new | Milestone:
Component: Uncategorized | Version: 1.2
Keywords: | Stage: Unreviewed
Has_patch: 0 |
---------------------------+------------------------------------------------
I tried use '''django.utils.decorators.method_decorator''' to support
decorator '''permission_required''' and figured out it's not supporting
decorators passing arguments like it does:
@permission_required(something_here)
Instead its code waits for you just pass a function as an only one
argument, like this:
@login_required
I made my own version of it, that's below:
{{{
from functools import wraps, update_wrapper
def method_decorator(decorator):
"""Converts a function decorator into a method decorator.
This works properly for both: decorators with arguments and without
them. The Django's version
of this function just supports decorators with no arguments."""
# For simple decorators, like @login_required, without arguments
def _dec(func):
def _wrapper(self, *args, **kwargs):
def bound_func(*args2, **kwargs2):
return func(self, *args2, **kwargs2)
return decorator(bound_func)(*args, **kwargs)
return wraps(func)(_wrapper)
# Called everytime
def _args(*argsx, **kwargsx):
# Detect a simple decorator and call _dec for it
if len(argsx) == 1 and callable(argsx[0]) and not kwargsx:
return _dec(argsx[0])
# Used for decorators with arguments, like
@permission_required('something')
def _dec2(func):
def _wrapper(self, *args, **kwargs):
def bound_func(*args2, **kwargs2):
return func(self, *args2, **kwargs2)
return decorator(*argsx, **kwargsx)(bound_func)(*args,
**kwargs)
return wraps(func)(_wrapper)
return _dec2
update_wrapper(_args, decorator)
# Change the name to aid debugging.
_args.__name__ = 'method_decorator(%s)' % decorator.__name__
return _args
}}}
If necessary I can make a patch and attach to this ticket.
--
Ticket URL: <http://code.djangoproject.com/ticket/13879>
Django <http://code.djangoproject.com/>
The Web framework for perfectionists with deadlines.
--
You received this message because you are subscribed to the Google Groups
"Django updates" group.
To post to this group, send email to [email protected].
To unsubscribe from this group, send email to
[email protected].
For more options, visit this group at
http://groups.google.com/group/django-updates?hl=en.