Adding an argument to a decorator
decorator, django, python
Solution
I hope this article by Bruce Eckel helps.
Upd: According to the article your code will look like this:
class no_share(object):
def __init__(self, arg1):
self.arg1 = arg1
def __call__(self, f):
"""Don't let them in if it's shared"""
# Do something with the argument passed to the decorator.
print 'Decorator arguments:', self.arg1
def wrapped_f(request, *args, **kwargs):
if kwargs.get('shared', True):
from django.http import Http404
raise Http404('not availiable for sharing')
f(request, *args, **kwargs)
return wrapped_f
to be used as desired:
@no_share('prefs')
def prefs(request, [...])
Problem
I have this decorator, used to decorate a django view when I do not want the view to be executed if the `share` argument is `True` (handled by middleware) ``` class no_share(object): def __init__(self, view): self.view = view def __call__(self, request, *args, **kwargs): """Don't let them in if it's shared""" if kwargs.get('shared', True): from django.http import Http404 raise Http404('not availiable for sharing') return self.view(request, *args, **kwargs) ``` It currently works like this: ``` @no_share def prefs(request, [...]) ``` But I'm wanting to expand the functionality a little bit, so that it will work like this: ``` @no_share('prefs') def prefs(request, [...]) ``` My question is how can I modify this decorator class so that it accepts extra arguments?