芹菜任务装饰器抛出“TypeError:”模块对象不可调用”

2024-06-25 23:27:19 发布

您现在位置:Python中文网/ 问答频道 /正文

我拼命想让芹菜和姜哥玩得很好,但没用。我被以下事情绊倒了:

项目/设置.py:

...

import djcelery
djcelery.setup_loader()

BROKER_URL = 'django://'
CELERY_RESULT_BACKEND = 'django://'
CELERY_TASK_SERIALIZER = 'json'
CELERY_RESULT_SERIALIZER = 'json'
CELERY_ENABLE_UTC = True

...

应用程序/任务.py:

from celery.task import task

@task()
def scheduled_task(param1, param2):
    ...
    return something

直接调用scheduled_task(param1, param2)(不使用decorator)按预期工作。然而,当添加装饰工并解雇“开发”芹菜工人时,就像这样:

python manage.py celery worker --loglevel=info

…我得到以下错误:

TypeError: 'module' object is not callable

我把这件事归咎于装饰工。我尝试的每个组合都失败,包括:

from celery import task
from celery.task import task
from celery.task.base import task

@task
@task()
@task.task
@task.task()
@celery.task
@celery.task()

异常中的调用堆栈似乎没有任何区别,它们都会认为task是一个模块,不可调用!更让人沮丧的是:

>>> from celery.task import task
>>> task
<function task at 0x10aa2a758>

对我来说真的很难接受!知道会发生什么吗?如果我遗漏了什么,我很乐意发布更多的日志、文件或澄清其他任何事情。


Tags: djangofrompyimportjsontaskresult事情
3条回答

这个问题有点老了,但我也遇到了类似的麻烦,这对我很有帮助:

项目/设置.py:

...

import djcelery
djcelery.setup_loader()

BROKER_URL = 'django://'
CELERY_RESULT_BACKEND = 'djcelery.backends.database:DatabaseBackend'
CELERY_TASK_SERIALIZER = 'json'
CELERY_RESULT_SERIALIZER = 'json'
CELERY_ENABLE_UTC = True

...

(转换为注释中的答案)

stack trace中,我认为return backend(app=self, url=url)行是发生异常的地方。

所以不管backend是什么,它似乎都不是可调用的。我将尝试在该文件(celery/app/base.py)中设置pdb断点,方法是将该行包装为

try:
    backend(app=self, url=url)
except:
    import pdb; pdb.set_trace(),

然后检查backend,向上移动堆栈(pdb中的u命令,d再次向下移动,w显示调用堆栈)以调试出错的地方。

celery docs也提到了这一点:

How do I import the task decorator?

The task decorator is available on your Celery instance, if you don’t know what that is then please read First Steps with Celery.

If you’re using Django or are still using the “old” module based celery API, then you can import the task decorator like this:

from celery import task

@task
def add(x, y):
    return x + y

因此,这应该可以澄清关于导入任务decorator的正确方法的任何含糊不清之处。

以防有人用芹菜拍,得到同样的错误信息。在我的应用程序中

command=/opt/python/run/venv/bin/celery beat -A appname --loglevel=INFO --workdir=/tmp -S django --pidfile /tmp/celerybeat.pid

得到了这个错误信息。由于我使用supervisord复制了大部分芹菜beat的守护代码(您需要一个特殊的配置),所以我没有意识到“-S django”假定使用了我以前没有安装过的django_芹菜beat包。我之所以安装它,是因为它对生产使用有好处,而且错误消失了。

相关问题 更多 >