首页 文章

Celery不会在django 1.11和芹菜4.0.0或4.1.0中发现shared_tasks

提问于
浏览
1

我在我的项目中有一个这样的布局:(正如文档所说的那样)

/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 -A后端worker -l info

enter image description here

正如您所看到的,我在tasks.py模块中的任务不会被celery进程读取,而是celery.py文件夹中的任务 .

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

我有两天的时间,这真的需要一些时间,任何帮助?

更新:(来自评论)'musics'是一个django应用程序,所以它有一个 __init__.py 文件 .

我也试过将应用程序名称传递给芹菜实例上的自动发现方法而没有任何运气 .

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

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

3 回答

  • 0

    musics 目录有 __init__.py 吗?

    另外,尝试明确指定包名称: app.autodiscover_tasks(['musics'])

    芹菜文档here

  • 0

    您的问题可能与您运行Celery的范围有关(例如:虚拟环境)

    例如,当我像这样经营芹菜时:

    celery -A demoproject worker --loglevel=info
    

    它仅输出一个任务(我的演示应用程序中唯一一个):

    [tasks]
      . core.tasks.demo
    

    但当我运行它 from the virtualenv 时,结果如下:

    [tasks]
      . core.tasks.demo
      . myapp.tasks.demo_task
    

    看到?它仅仅因为环境而发现了一个新的应用程序 .

  • 1

    我找到了一个解决方案,我只是在 celery.py 文件中导入模块(Django App),它会读取所有任务 .

    但是,这不是celery文档中描述的行为

相关问题