gpt4 book ai didi

Python 自定义装饰器不适用于 Celery 任务

转载 作者:太空宇宙 更新时间:2023-11-03 14:02:26 24 4
gpt4 key购买 nike

<分区>

我在使用 Python 装饰器时遇到了一些麻烦。我有一个这样设置的场景:

def decorated(func):
def call_and_update(*args, **kwargs):
# do some stuff here
output = func(*args, **kwargs)
# do more stuff here
return output
return call_and_update

@celery.task
@decorated
def testA():
return "Test A"

@celery.task
@decorated
def testB():
return "Test B"

出于某种原因,无论我先调用哪个函数,似乎都作为装饰器中的 func 保留。

例如,如果我启动一个 shell 并运行:

>>> testA()
Test A
>>> testB()
Test A

或者,如果我重新启动 shell 并开始第二个测试:

>>> testB()
Test B
>>>> testA()
Test B

我找到了 this question with a similar issue ,但少数答案围绕着为任务方法使用扩展类。

如果我特别想通过装饰器和函数来做到这一点,有什么技巧可以让它发挥作用吗?

请注意,没有 @celery.task 装饰器,函数将正常工作。特别是两个装饰器的组合导致了问题。

谢谢!

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com