I have log in system, based on OpenID provider, and I want to create decorator like @login_required. But I have a problem - I need to check permission per object. I pass id to my views, so I want to know is there any way to pass it to decorator or it's impossible and I need to check users permission in my view.
Asked
Active
Viewed 1,833 times
1
-
1Possible duplicate of [Understanding Python decorators](http://stackoverflow.com/questions/739654/understanding-python-decorators). It's an old post, but it has a lot of good information on it. – Jeremy Aug 20 '11 at 21:20
-
Yes, thanks, I'm looking for Django decorators so miss this article. It really helps me. – Lertmind Aug 20 '11 at 21:37
2 Answers
3
def outer(var1, var2):
def inner(func)
func.foo = var1
func.bar = var2
return func
return inner
@outer(myvar1, myvar2)
def myfunc():
# whatever
pass
While you can't pass variables directly to the function which decorates your function, you can create another function (outer
) that, when called, returns the decorating function (inner
). You pass the outer
function variables, and they are available to the inner
function. This is called a closure.

agf
- 171,228
- 44
- 289
- 238
3
Depending on when you need to do the stuff with the id you may need two levels of wrapping where you replace print(permission_id)
with whatever it is you need to do before the method is called:
def login_required(permission_id):
def decorator(func):
def method(self, *args, **kw):
print(permission_id)
return func(self, *args, **kw)
return method
return decorator
class foo(object):
@login_required('foo')
def bar(self):
print('bar')
foo = foo()
print('instantiated')
foo.bar()
Outputs:
instantiated
foo
bar

Ross Patterson
- 5,702
- 20
- 38
-
perhaps the most interesting thing is that defined function "method" is a **real method**. self reference behaves as expected, exposing a live object to play with. – Adam Kurkiewicz Oct 13 '13 at 23:36