我有一个运行检查的类,每个函数执行一次检查。我想过装饰器添加额外的条件,但这可能并不明智。
我理解装饰器的概念,每个装饰器都将其装饰的函数作为输入并返回到下一个装饰的函数。这对于返回字符串的函数来说效果很好,因为输出可以很容易地由装饰器编辑并返回给下一个装饰器。
我想做的是修改函数属性,例如放置一个 don't exec
标志来表示不运行检查,require auth
表示仅在以下情况下执行的检查已授予身份验证,或更改函数属性 order
,以顺序检查启动。
# I return f only if is_authenticated flag is True
def auth_required(is_authenticated):
def check_authentication(f):
if is_authenticated:
return f
return check_authentication
# I edit order variable
def assignOrder(order):
def do_assignment(f):
f.order = order
return f
return do_assignment
# I instanciate Checks class and provide authentication;
# login and password will be tried and is_authenticat flag set accordingly
c = Checks(target, login, password)
# I sort on order variable and launch checks
functions = sorted(
[
getattr(c, field) for field in dir(c)
if hasattr(getattr(c, field), 'order')
],key = (lambda field : field.order)
)
for function in functions:
function()
# I assign decorators so that order variable is set
# I would like auth_required triggers launch if auth is performed
@auth_required(True)
@assignOrder(100)
def check_shares(self):
# check defined here
这对 assignOrder 非常有用,我的检查以正确的顺序启动。
但是 @auth_required
应用于 assignOrder
这不是我想要的。
有没有办法找回要装饰的原始函数?或者装饰器的使用在这种情况下不相关?解决方案是什么?
非常感谢
最佳答案
没有解决问题的通用方法。装饰器没有内置的协作工具,甚至不需要保留对原始函数的引用。
所以你需要自己想出一个协议(protocol),例如使 assignOrder
将原始函数保存到 do_assignment
。
然后在 is_authenticated
中,你必须查看传递的函数背后是否有一个“真正的”函数,然后使用它。
关于python - 多个 python 装饰器检索原始函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30639854/