【问题标题】:Is it possible to add a parameter to a function with a decorator in Python?是否可以在 Python 中使用装饰器向函数添加参数?
【发布时间】:2021-03-28 13:22:39
【问题描述】:

所以我尝试编写一个装饰器函数来保护对具有“密码字符串”auth 的函数的访问。装饰器函数如下所示:

from functools import wraps

def decorator(func):
    @wraps(func)
    def wrapper(*args, **kwargs):
        if "auth" in kwargs.keys():
            if kwargs["auth"] == "12345":
                func(*args, **kwargs)
                return
        print("Not authorized.")

    return wrapper

我要保护的示例函数的定义如下所示:

@decorator
def add(list, elem, auth):
    list.append(elem)

在我的主代码中,我像这样调用add()

def main():
    lst = [3,5]
    add(lst, 2, auth="12345")
    print(lst)


if __name__ == "__main__":
    main()

我的目标是能够做到这一点,而无需在 add() 的定义中明确提及 auth,所以我可以这样做:

@decorator
def add(list, elem):
    list.append(elem)

这可能吗?

【问题讨论】:

  • 试试看...
  • 它最终应该有多安全?
  • @MattDMo 好吧,我不知道怎么做,这就是我问的原因。只是从add() 的参数列表中删除auth 显然是行不通的,但我认为可能还有另一种解决方案。
  • @lucidbrot 这只是练习,不是真正的安全问题。

标签: python python-3.x decorator python-decorators


【解决方案1】:

你应该可以得到你想要的:

if kwargs.pop("auth", None) == "12345":

您需要删除 "auth" 参数,因为您正在使用它并且不想将其传递给孩子。

你也应该替换

func(*args, **kwargs)
return

return func(*args, **kwargs)

如果你碰巧调用了一个返回值的函数。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2010-12-23
    • 2022-06-20
    • 2013-09-14
    • 2013-01-14
    • 1970-01-01
    • 2022-01-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多