即使没有调用`app.autodiscover_tasks()`,Celery也会发现所有任务

时间:2018-06-11 12:19:00

标签: django celery celery-task

我正在使用Django==2.0.5celery==4.0.2。 我的proj/proj/celery.py看起来像是:

from __future__ import absolute_import, unicode_literals
import os
from celery import Celery

# set the default Django settings module for the 'celery' program.
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'proj.settings')

app = Celery('proj', include=[])

# Using a string here means the worker doesn't have to serialize
# the configuration object to child processes.
# - namespace='CELERY' means all celery-related configuration keys
#   should have a `CELERY_` prefix.
app.config_from_object('django.conf:settings', namespace='CELERY')

# Load task modules from all registered Django app configs.
# app.autodiscover_tasks()


@app.task(bind=True)
def debug_task(self):
    print('Request: {0!r}'.format(self.request))

我原本预计应用程序shared_task中的tasks.py所包含的任务都不会被发现,但令我惊讶的是,大多数任务都可以在[tasks]下看到celery workercelery worker -A proj -l INFO

我的目录结构有点像:

app
│   ├── __init__.py
│   ├── admin.py
│   ├── apps.py
│   ├── constants.py
│   ├── scripts
│   │   ├── __init__.py
│   ├── factories.py
│   ├── migrations
│   │   ├── 0001_initial.py
│   │   ├── __init__.py
│   ├── models.py
│   ├── tasks.py
│   └── tests
│       ├── __init__.py

CELERY_IMPORTS未在settings.py中设置,我甚至尝试使用CELERY_IMPORTS=()CELERY_IMPORTS=['path/to/one/of/the/modules'],即使这样,所有任务都会被发现。

欢迎提出任何建议。

1 个答案:

答案 0 :(得分:0)

你应该在没有(bind = True)标志的情况下尝试@ app.task。 如果celery位于模块的 init 文件中,它也可以检测模块内的所有任务。在django settings.py

CELERY_IMPORTS=("path/to/module",) 

将导致发现该模块中的所有内容。确保你没有做过类似的事情。

您还可以共享项目文件夹结构吗?