use*_*943 10 python django signals celery
我以前有这样的功能
def calculate(self, input):
result = input * 2
if result > 4:
result_higher_then_four.send(result)
return result
Run Code Online (Sandbox Code Playgroud)
其中result_higher_then_four显然代表的信号.
然后我介绍了芹菜,我的功能看起来像下面,我再也没有收到过信号.我想每个过程都会绑定信号,并且芹菜在不同的过程中运行,这意味着我无法捕获主过程中的信号.我应该用a thread_local来解决这个问题吗?还是我忽略了明显的?
谢谢
@task
def calculate(self, input):
result = input * 2
if result > 4:
result_higher_then_four.send(result)
return result
Run Code Online (Sandbox Code Playgroud)
问题是信号接收器没有注册。芹菜工作人员在自己的进程中运行,因此需要在该进程中建立信号连接。如果您知道它们是什么或可以发现它们,则可以使用此技术在任务初始化期间注册它们。
当然,这首先消除了使用信号的一些好处,因为您需要提前了解连接。
一种想法是假设信号接收器将始终在每个应用程序的模型模块中注册。在这种情况下,以下内容将起作用。
class CalculateTask(celery.Task):
def __init__(self):
from django.conf import settings
for app in settings.INSTALLED_APPS:
app_models = '{}.{}'.format(app,'models')
__import__(app_models, globals=globals())
def run(self, input):
result = input * 2
if result > 4:
result_higher_then_four.send(result)
return result
Run Code Online (Sandbox Code Playgroud)