芹菜任务延迟导致的键盘错误

Keyerror from celery task delay

celery getting started with Django instructions 之后,我能够 运行 任务,但不能 运行 使用 delay() 异步执行同一任务。

我在我的 Django 项目中添加了以下要求:

celery==4.3.0
redis==3.3.11
django-celery-results==1.1.2
psycopg2==2.7.3.1
django-cors-headers~=3.1.0

在 pop_model 项目目录中创建此 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', 'pop_model.settings.local')

app = Celery('pop_model')

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

在项目中插入这段代码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',)

在项目设置中配置了 cors 并添加了这些设置:

CELERY_BROKER_URL = 'redis://localhost:6379'
CELERY_RESULT_BACKEND = 'django-db' # defined in django_celery_results

CELERY_ACCEPT_CONTENT = ['json']
CELERY_RESULT_SERIALIZER = 'json'
CELERY_TASK_SERIALIZER = 'json'

我可以启动 redis,然后 运行 celery 使用这些命令:

export DJANGO_SETTINGS_MODULE=pop_model.settings.local
celery worker -A pop_model --loglevel=info

在 python3 shell 中,我得到了这些结果:

>>> from pop_model.celery import debug_task
>>> debug_task()
Request: <Context: {'args': (), 'kwargs': {}}>
>>> task=debug_task.delay()
Traceback (most recent call last):
  File "/Users/janee/.virtualenvs/pop-model/lib/python3.6/site-packages/kombu/utils/objects.py", line 42, in __get__
    return obj.__dict__[self.__name__]
KeyError: 'backend'

我不知道如何解决丢失的 backend 键,因为 CELERY_RESULT_BACKEND 在设置文件中定义。

普通 Python shell 和 manage.py shell 之间的唯一区别是它在 DJANGO_SETTINGS_MODULE 环境变量中导出您的设置模块 (project_name.settings) .

如果您 运行 具有正确环境变量的同一个解释器,您应该看不到任何变化。然后,可能是您的 pop_model.settings.local 路径没有返回正确的设置模块供您的应用程序锁定,或者您正在使用修改后的 manage.py 脚本(我想是为了开发环境分离),其中设置模块已正确加载。

您应该可以使用

调用您的函数
./manage.py shell

从您的项目目录,使用与您的虚拟环境相同的解释器。这也可以工作,因为 DJANGO_SETTINGS_MODULE 需要解释器搜索路径中存在的路径(关于 here 的更多信息)并且您可以从另一个目录调用解释器。