在 Django 中使用简单异步队列的最佳方式?

Best way to use simple asynchronous queues in django?

我需要我的 django 视图函数来触发一个任务,然后该任务将 运行 在后台运行,而不是阻止响应。

def my_task(client_information, unique_id): # task
    #do something that takes a while

def my_view(request): # django view

    client_information = request.GET.get('whatever') # get some information passed from the client
    unique_id = generate_unique_id() # generate a unique ID for this task
    start_task(client_information, unique_id) # the interesting part: start the task with client information and unique id, but non blocking
    return JsonResponse({'id': unique_id})

我阅读了有关 celery 的内容,但我看到的代码看起来有些过分,因为我不需要进程之间的任何进一步通信,而且我真的想要一个尽可能轻量级的解决方案。

Django Background Tasks 是一个简单的 database-based 队列,它只需要一个 worker 运行ning 在后台(通过 manage.py process_tasks 调用)。如果您永远不会利用 Celery 的好处,我认为这就是您正在寻找的轻量级解决方案。

安装扩展后,您可以定义一个方法并为它们添加一个 @background(schedule=20) 装饰器,这将使它们自动在后台 运行。有关详细信息,请参阅 upstream docs