Is there a way to pass variables to decorator?
I have log in system开发者_JS百科, 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.
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.
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
精彩评论