简体   繁体   English

有没有办法将变量传递给装饰器?

[英]Is there a way to pass variables to decorator?

I have log in system, based on OpenID provider, and I want to create decorator like @login_required. 我已经基于OpenID提供程序登录系统,并且想要创建类似@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. 我将id传递给我的视图,所以我想知道有什么方法可以将其传递给装饰器,否则这是不可能的,我需要在视图中检查用户权限。

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 ). 虽然您不能将变量直接传递给装饰函数的函数,但是可以创建另一个函数outer ),该函数在调用时返回装饰函数inner )。 You pass the outer function variables, and they are available to the inner function. 您传递outer函数变量,它们对于inner函数可用。 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: 根据何时需要使用id进行操作,您可能需要两层包装,在其中将print(permission_id)替换为调用方法之前需要执行的操作:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM