Celery Django 未注册任务,shell 中未找到模块错误
Posted
技术标签:
【中文标题】Celery Django 未注册任务,shell 中未找到模块错误【英文标题】:Celery Django not Registering Tasks, Module not found error in shell 【发布时间】:2015-12-01 15:04:35 【问题描述】:我正在尝试从 Celery 文档中运行一个基本示例,但是当我运行“从任务导入添加”时,它给了我一个错误,提示“找不到模块”。
这些是我更改的文件。
proj/proj/celery.py
from __future__ import absolute_import
import os
from celery import Celery
# set the default Django settings module for the 'celery' program.
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'proj.settings')
from django.conf import settings
app = Celery('proj')
# Using a string here means the worker will not have to
# pickle the object when using Windows.
app.config_from_object('django.conf:settings')
app.autodiscover_tasks(lambda: settings.INSTALLED_APPS)
@app.task(bind=True)
def debug_task(self):
print('Request: 0!r'.format(self.request))
proj/proj/settings.py
BROKER_URL = 'amqp://guest:guest@localhost//'
#: Only add pickle to this list if your broker is secured
#: from unwanted access (see userguide/security.html)
CELERY_ACCEPT_CONTENT = ['json']
CELERY_TASK_SERIALIZER = 'json'
CELERY_RESULT_SERIALIZER = 'json'
INSTALLED_APPS = (
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'celerymod',
'djcelery',
)
proj/proj/init.py
from __future__ import absolute_import
from .celery import app as celery_app
proj/celerymod/tasks.py
from __future__ import absolute_import
from celery import shared_task
@shared_task
def add(x, y):
return x + y
@shared_task
def mul(x, y):
return x * y
@shared_task
def xsum(numbers):
return sum(numbers)
感谢任何建议。谢谢!
【问题讨论】:
【参考方案1】:我遇到了同样的问题,
我在应用中的任务没有注册。
我可以通过将 celery.py 的导入移动到 settings.py 而不是 init.py 来解决此问题
proj/proj/init.py
from __future__ import absolute_import
# is empty
proj/proj/settings.py
from .celery import app as celery_app
BROKER_URL = 'amqp://guest:guest@localhost//'
#: Only add pickle to this list if your broker is secured
#: from unwanted access (see userguide/security.html)
CELERY_ACCEPT_CONTENT = ['json']
CELERY_TASK_SERIALIZER = 'json'
CELERY_RESULT_SERIALIZER = 'json'
INSTALLED_APPS = (
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'celerymod',
'djcelery',
)
【讨论】:
【参考方案2】:如果其他人有同样的问题。在外壳中执行此操作。 myapp 是应用程序的名称,在我的例子中是 proj。
from myapp.tasks import add
【讨论】:
它有什么帮助?请您进一步澄清一下。以上是关于Celery Django 未注册任务,shell 中未找到模块错误的主要内容,如果未能解决你的问题,请参考以下文章
celery - 尽管已注册,但任务未运行。芹菜控制台不反映任务的接收
未执行的任务(Django + Heroku + Celery + RabbitMQ)