2017-04-18 104 views
0

我写了一个登录装饰器,应该保证在执行另一个函数之前用户已正确登录。问题是,虽然装饰器正在按预期工作,但函数包装函数从不执行。我的结构如下所示: 修饰器不调用封装函数

#This is my decorator 
login_required(func): 
    def func_wrapper(*args, **kwargs): 
     #do some operations 
     return True #or False 
    return func_wrapper 

@login_required 
def do_something(param1, param2, param3): 
    print("This print is not executing") 
    #continue the work that should be done after 
    #the user is authorized by the login decorator 

我已经试图删除返回True /装饰里面假的,但它并没有改变任何东西。

回答

3

您的包装函数从未调用func。如果你想func在调用包装时调用,调用它,例如:

def login_required(func): 
    def func_wrapper(*args, **kwargs): 
     #do some operations to determine if user logged in and allowed to do op 
     if allowed: 
      return func(*args, **kwargs) 
     else: 
      # Raise exception, return "auth required" sentinel value, whatever 
    return func_wrapper 

你的代码是假设返回一个布尔值会以某种方式确定包裹func是否被调用,但这是装饰而不是如何工作。他们替换与装饰器返回的任何原始函数;如果你返回一个新函数,那个新函数负责调用原始函数(如果需要的话),其他人不会为你做。

+0

哦,那太愚蠢了。我从来没有称过我的函数func,所以显然没有被调用。非常感谢你! – Depa