我的 Celery 任务正在执行,但它没有在工作人员中执行

My Celery task is executing but it does not execute in a worker

我有一个 Django 应用程序,它有一个 api 应用程序,允许传入请求触发 celery 任务,同时 return 对请求作出响应。 celery 任务完成后,它会写入文件。

在我的应用程序中,我有:

view.py

from api.tasks import *
from codegen import celery_app

def index(request, product_id, amount_to_gen):
    response_data = {}
    generateCodes(product_id, amount_to_gen)
    response_data['result'] = 'success'
    response_data['reason'] = 'The server has successfully received your request'
    return JsonResponse(response_data)

tasks.py

from __future__ import absolute_import
from codegen import celery_app

@celery_app.task()
def generateCodes(product_id, amount_to_gen):
    **code to generate random uniqque codes then put them in a file**

在开始请求之前,我启动了 Apache 并且 运行

python manage.py celery worker -E

然后发送请求。请求 return 是响应,但它仅在它 运行 是 generateCodes 方法之后才这样做,并且 celery worker 的控制台上没有任何显示。

问题

如何获取请求到return响应并在后台生成代码文件?

generateCodes.apply_async(args=[product_id, amount_to_gen])

如果你 运行 它喜欢 generateCodes(..) 它会 运行 它作为一个正常的阻塞方法。

当您调用 generateCodes(product_id, amount_to_gen) 时,您正在绕过 Celery 的分布式设施。

为了方便起见,Celery 定义了它的任务对象,这样简单地调用任务就会调用任务,就像调用 Python 中的任何函数一样。这是描述 here:

calling (__call__)

Applying an object supporting the calling API (e.g. add(2, 2)) means that the task will be executed in the current process, and not by a worker (a message will not be sent).

注意它是怎么说“不是由工人”的。那是你的问题。您必须调用 generateCodes.apply_async(product_id, amount_to_gen) 才能让工作人员执行您的任务。