【发布时间】:2019-01-06 03:34:03
【问题描述】:
我想用code available here检查official demo Celery project for django中的基本Celery功能。
我的修改是demoapp/views.py(当然还有urls.py指向这个视图):
from __future__ import absolute_import, unicode_literals
from django.http import HttpResponse
from demoapp.tasks import add, mul, xsum
def home(request):
return HttpResponse("Your output is: %s" % mul.delay(22,4).get(timeout=1) )
虽然运行 Celery worker 的终端显示任务已收到并显示正确的返回值,但它总是给出超时错误。
但是,如果我启动 python shell python ./manage.py shell 然后运行
from demoapp.tasks import add, mul, xsum
mul.delay(22,4).get(timeout=1)
我立即得到预期的结果。可能是什么问题?
Rabbitmq 服务器正在运行,我使用 Celery 4.2.1,django 2.0.6。
demoapp/tasks.py:
from __future__ import absolute_import, unicode_literals
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)
项目/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', 'proj.settings')
app = Celery('proj')
# 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))
项目/settings.py
...
CELERY_BROKER_URL = 'amqp://guest:guest@localhost//'
CELERY_ACCEPT_CONTENT = ['json']
CELERY_RESULT_BACKEND = 'db+sqlite:///results.sqlite'
CELERY_TASK_SERIALIZER = 'json'
...
【问题讨论】:
-
您为什么要这样做?即使作为测试,它似乎完全错过了芹菜的意义。
-
这只是为了检查 django 和 celery 是否一起工作。真正的应用程序当然是异步的。
标签: python django celery django-celery