python - Celery 在 django 1.11 和 celery 4.0.0 或 4.1.0 中不会发现共享任务

标签 python django celery django-celery

我的项目中有这样的布局:(正如文档所说,它必须如此)

/zonia
    /backend
        __init__.py
        celery.py
        ...
    /musics
    tasks.py
    ...
...

init.py中:

from __future__ import absolute_import, unicode_literals

# This will make sure the app is always imported when
# Django starts so that shared_task will use this app.
from .celery import app as celery_app

__all__ = ['celery_app']

在 celery.py 中:

from __future__ import absolute_import, unicode_literals

import os

import environ
from celery import Celery

env = environ.Env()
environ.Env.read_env()
# set the default Django settings module for the 'celery' program.
os.environ.setdefault('C_FORCE_ROOT', 'true')
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'backend.settings')

app = Celery('backend', backend='rpc://', broker=env('broker'))

# Using a string here means the worker don'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))

我的tasks.py模块中有几个shared_tasks,如下所示:

@shared_task
def recalc_ranking_music():
    musics = musics_models.Music.objects.all().order_by("-num_points")
    for music, rank in enumerate(musics):
        music.ranking = rank + 1
        music.save()

当我使用命令启动 celery 时:celery -A backend worker -l info

enter image description here

如您所见,我在tasks.py模块中的任务不会被celery进程读取,但celery.py文件夹中的任务会被读取。

奇怪的是,我在另一个项目中具有完全相同的布局,并且工作正常。

我有两天的时间来处理这个问题,这确实花了一些时间,有什么帮助吗?

更新:(来自评论)“musics”是一个 django 应用程序,因此它有一个 __init__.py 文件。

我还尝试将应用程序名称传递给 celery 实例上的自动发现方法,但没有任何运气。

如果我在 app.autodiscover_tasks(force=True) 中设置,它会抛出错误:

django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet.

最佳答案

你的musics目录有__init__.py吗?

此外,尝试显式指定包名称: app.autodiscover_tasks(['音乐'])

Celery 文档 here

关于python - Celery 在 django 1.11 和 celery 4.0.0 或 4.1.0 中不会发现共享任务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45765736/

相关文章:

python - 运行时警告: You're running the worker with superuser privileges: this is absolutely not recommended

python - 无法从 PySpark 将 Spark 数据帧保存到 Google Cloud Storage

python - python 中的 __str__ 方法

python - pyparsing:无法从 ParseResults 对象获取结果

python - 为什么我的pyinstaller python程序在双击而不是在cmd运行时崩溃

python - 如何使用 django View 中所需的注销之类的东西?

python - Django:按用户配置文件或外键过滤

python - psycopg2 错误 : DatabaseError: error with no message from the libpq

postgresql - 为什么我的 Airflow 任务已排队但未运行?

python - 为什么不使用 django-admin startapp mysite 生成 urls.py?