我正在努力解决 celery 没有按照其文档声称的那样做的问题:我有一个 DJango 1.9 应用程序,我正在运行 celery 3.1.20,并且我有以下内容:
我的应用程序/celery.py:
from __future__ import absolute_import
import os
from celery import Celery
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'myapp.settings')
from django.conf import settings # noqa
app = Celery('myapp')
app.config_from_object('django.conf:settings')
myapp/jobs/tasks.py:
from myapp.celery import app
class Job1(app.Task):
...
name = 'job_1'
...
class Job2(app.Task):
...
name = 'job_2'
...
不过,我都试过了:
我的应用程序/settings.py:
CELERY_IMPORTS = ('myapp.jobs.tasks',)
和
我的应用程序/celery.py:
app.autodiscover_tasks(lambda: settings.INSTALLED_APPS)
而且都没有正确注册我的任务。只有在我手动导入定义任务的模块后,任务才会显示在 app.tasks 中,因此当我使用任务以确保它已加载时,我不得不做一个丑陋的本地导入 hack。
在 django shell 中:
In [1]: from myapp.celery import app
In [2]: app.tasks
Out[2]:
{'celery.backend_cleanup': <@task: celery.backend_cleanup of myapp:0x10dc260d0>,
'celery.chain': <@task: celery.chain of myapp:0x10dc260d0>,
'celery.chord': <@task: celery.chord of myapp:0x10dc260d0>,
'celery.chord_unlock': <@task: celery.chord_unlock of myapp:0x10dc260d0>,
'celery.chunks': <@task: celery.chunks of myapp:0x10dc260d0>,
'celery.group': <@task: celery.group of myapp:0x10dc260d0>,
'celery.map': <@task: celery.map of myapp:0x10dc260d0>,
'celery.starmap': <@task: celery.starmap of myapp:0x10dc260d0>}
In [3]: app.conf['CELERY_IMPORTS']
Out[3]: ('myapp.jobs.tasks',)
In [4]: from myapp.jobs import tasks
In [5]: app.tasks
Out[5]:
{'celery.backend_cleanup': <@task: celery.backend_cleanup of myapp:0x10dc260d0>,
'celery.chain': <@task: celery.chain of myapp:0x10dc260d0>,
'celery.chord': <@task: celery.chord of myapp:0x10dc260d0>,
'celery.chord_unlock': <@task: celery.chord_unlock of myapp:0x10dc260d0>,
'celery.chunks': <@task: celery.chunks of myapp:0x10dc260d0>,
'celery.group': <@task: celery.group of myapp:0x10dc260d0>,
'celery.map': <@task: celery.map of myapp:0x10dc260d0>,
'celery.starmap': <@task: celery.starmap of myapp:0x10dc260d0>,
'job_1': <@task: job_1 of myapp:0x10dc260d0>,
'job_2': <@task: job_2 of myapp:0x10dc260d0>,
'job_3': <@task: job_3 of myapp:0x10dc260d0>}
知道这里发生了什么吗?在我自己导入模块之前,它不会加载任务。
提前致谢。
请您参考如下方法:
遇到了同样的问题,并将有问题的应用程序的 settings.py 中 INSTALLED_APPS 下的应用程序配置的虚线 python 路径更改为应用程序模块的名称,它似乎可以工作(目前) .在 Django 1.9 中,看起来 INSTALLED_APPS 可以采用指向应用程序配置文件的带点的 python 路径,或者像早期版本一样只是模块名称。
