【问题标题】:How to implement callbacks asynchronously in Django?如何在 Django 中异步实现回调?
【发布时间】:2019-11-15 12:01:14
【问题描述】:

我正在使用 Django 构建一个网络应用程序,它有两个部分:

  1. 部署 docker 容器并将过期时间存储在数据库中,
  2. 根据到期时间杀死它们,但是,应用程序的用户可以选择延长容器的寿命。

如何在不轮询数据库的情况下实现第二部分?

我尝试使用 asyncio 并在 Django 中实现了一个自定义中间件,但它阻止了执行。有没有其他方法可以异步完成这项工作。

import asyncio
from threading import Thread


def callback_func(eventloop):
    """
    check DB
    if now:
        kill
    else:
        register a new callback with new updated time 
    """
    # Logic to kill a container goes here

    print ("Inside callback")


class KillerMiddleware:

    def __init__(self, get_response):
        self.get_response = get_response
        self._eventloop = asyncio.new_event_loop()
        asyncio.set_event_loop(self._eventloop)

        self._t = Thread(target=lambda : self._eventloop.run_forever())
        self._t.daemon = True
        self._t.start()


    def __call__(self, request):

        response = self.get_response(request)

        self._eventloop.call_later(86400, callback_func, self._eventloop)
        return response

【问题讨论】:

    标签: django python-3.x python-asyncio


    【解决方案1】:

    我真的不太了解python-asyncio,但听起来Django Channels 很适合。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-12-10
      • 1970-01-01
      • 2014-06-09
      • 2022-08-18
      • 2019-08-03
      • 1970-01-01
      • 2018-03-14
      相关资源
      最近更新 更多