【问题标题】:Django - Celery with RabbitMQ: task always remains in PENDINGDjango - 带有 RabbitMQ 的 Celery:任务始终处于待处理状态
【发布时间】:2017-12-25 03:56:07
【问题描述】:

我必须使用 Celery 4.0.2 和 RabbitMQ 3.6.10 来处理异步任务。然后,我遵循了这个教程:https://www.codementor.io/uditagarwal/asynchronous-tasks-using-celery-with-django-du1087f5k

但是,我的任务有点小问题,因为不可能有结果。我的任务始终处于“PENDING”状态。

我的问题是我必须做什么才能得到结果?

提前感谢您的回答。

这是我的代码:

这里是我的 __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']

这是我的setting.py的一部分:

BROKER_URL = 'amqp://guest:guest@localhost//'
CELERY_ACCEPT_CONTENT = ['json']
CELERY_TASK_SERIALIZER = 'json'
CELERY_RESULT_SERIALIZER = 'json'

这里是我的 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', 'mysite.settings')

app = Celery('mysite',
    backend='amqp',
    broker='amqp://guest@localhost//')

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

还有我的tasks.py

# Create your tasks here
from __future__ import absolute_import, unicode_literals
from celery import shared_task


@shared_task
def add(x, y):
    test = "ok"
    current_task.update_state(state='PROGRESS',
        meta={'test': ok})
    return x + y

这里是我的 Django Shell:

>>> from blog.tasks import *
>>> job = add.delay(2,3)
>>> job.state
'PENDING'
>>> job.result
>>>

附上我的 RabbitMQ 界面图片:

【问题讨论】:

    标签: django asynchronous rabbitmq celery


    【解决方案1】:

    您需要启动一个工作程序来处理您添加到队列中的任务。从你的 virtualenv 运行:

    celery worker -A blog -l info
    

    【讨论】:

    • 感谢您的快速回答,见下文。
    猜你喜欢
    • 2014-09-20
    • 1970-01-01
    • 2019-05-27
    • 2011-11-01
    • 1970-01-01
    • 2020-12-04
    • 2015-07-14
    • 2012-09-18
    • 1970-01-01
    相关资源
    最近更新 更多