【问题标题】:decorator not calling the wrapped function装饰器不调用包装函数
【发布时间】:2017-09-13 17:21:51
【问题描述】:

我写了一个登录装饰器,它应该保证用户在执行另一个功能之前正确登录。问题是,尽管装饰器按预期工作,但函数包装的函数永远不会执行。我的结构如下:

#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/False,但它没有改变任何东西。

【问题讨论】:

    标签: python decorator python-decorators


    【解决方案1】:

    你的包装函数永远不会调用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 是否被调用,但这不是装饰器的工作方式。他们用装饰器返回的任何东西替换原始函数;如果您返回一个新函数,则该新函数负责调用原始函数(如果需要),其他人不会为您执行此操作。

    【讨论】:

    • 哦,那真是愚蠢。我从未调用过我的函数 func,所以它显然从未被调用过。非常感谢!
    猜你喜欢
    • 2018-03-07
    • 2011-06-25
    • 2017-11-05
    • 2018-06-11
    • 2021-04-06
    • 1970-01-01
    • 1970-01-01
    • 2020-04-28
    相关资源
    最近更新 更多