即使未调用`app.autodiscover_tasks()`,Celery也会发现所有任务 [英] Celery discovers all tasks even when `app.autodiscover_tasks()` is not called

查看:283
本文介绍了即使未调用`app.autodiscover_tasks()`,Celery也会发现所有任务的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 Django == 2.0.5 celery == 4.0.2 .我的 proj/proj/celery.py 如下:

I am using Django==2.0.5 and celery==4.0.2. My proj/proj/celery.py looks like:

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))

我期望在应用程序的 tasks.py 中找不到被 shared_task 装饰的任务,但令我惊讶的是,大多数任务都可以看到在与 celery worker -A proj -l INFO 一起运行 celery worker 时,在 [tasks] 下.

I was expecting that none of the tasks decorated with shared_task in tasks.py of the apps will be discovered but to my surprise, most of the tasks can be seen under [tasks] when running celery worker with celery 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 = ['路径/到/一个///模块的]],甚至所有任务都被发现.

CELERY_IMPORTS is not set in settings.py and I have even tried with CELERY_IMPORTS=() and CELERY_IMPORTS=['path/to/one/of/the/modules'], even then all the tasks get discovered.

欢迎任何建议.

推荐答案

您应尝试使用不带(bind = True)标志的@ app.task.如果celery位于模块的 init 文件中,它们也可以检测到模块中的所有任务.在django settings.py

You should try @app.task without the (bind=True) flag. Also celery can detect all the tasks inside a module if they are in the init file of the module. In the django settings.py

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

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

will cause to discover everything in that module. Make sure you haven't done something similar.

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

Can you also share the project folder structure?

这篇关于即使未调用`app.autodiscover_tasks()`,Celery也会发现所有任务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆