【问题标题】:Best way to use simple asynchronous queues in django?在 django 中使用简单异步队列的最佳方法?
【发布时间】:2021-01-15 11:59:45
【问题描述】:

我需要我的 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 的文章,但我看到的代码看起来有点过头了,因为我不需要进程之间的任何进一步通信,我真的想要一个尽可能轻量级的解决方案。

【问题讨论】:

    标签: python django asynchronous queue celery


    【解决方案1】:

    Django Background Tasks 是一个简单的基于数据库的队列,只需要一个在后台运行的工作人员(通过manage.py process_tasks 调用)。如果您永远不会利用 Celery 的优势,我认为这是您正在寻找的轻量级解决方案。

    安装扩展后,您可以定义一个方法并向它们添加一个@background(schedule=20) 装饰器,这将使它们自动在后台运行。详情请见upstream docs

    【讨论】:

    • 谢谢!我接受了这个答案,因为我认为它为我的问题提出了一个有效的解决方案。现在,我正在尝试使用这个peter-hoffmann.com/2012/python-simple-queue-redis-queue.html 来解决问题。如果我遇到问题或对结果不满意,我将使用此解决方案。
    猜你喜欢
    • 2017-04-24
    • 2017-02-25
    • 2010-10-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-12-31
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多