Django通道执行命令

2024-04-24 04:36:47 发布

您现在位置:Python中文网/ 问答频道 /正文

我需要一些帮助来理解Django通道是如何执行代码的。我可能对sync和async缺少一些理解,因为它没有达到我所期望的效果。你知道吗

总而言之,我希望消费者能够做到以下几点:

  1. 连接
  2. 来自客户端的消息
    • 在while循环中:
      • 执行长时间运行的函数(1秒)
      • 调用group_send广播结果

这是行不通的,所以我试图创建一个非常简单的消费者来了解发生了什么。你知道吗

我创建了一个WebsocketConsumer,就像我想让它运行syncronously,也就是说,我希望每个循环执行,然后广播结果,然后再次执行。你知道吗

当我触发receive方法时,我看到self.send会立即发生,但这两个方法都是“2。第一组呼叫“”3。第二个组调用“发生在长时间运行的函数之后。我可以从console.log中的时间戳看出,chat_message()只针对“2执行。在长时间运行的函数之后的第一个组调用“,即使它出现在receive方法中长时间运行的函数之前。你知道吗

其中一个浏览器控制台中的结果是:

  1. 收到“1。自动发送21:45:22.060500
  2. 收到“2。21:45:22.060500第一次群呼聊天开始时间:21:45:24.529500”
  3. 收到“3。21:45:22.060500第二组发送lrf开始时间:21:45:22.348000 lrf结束时间:21:45:24.349500聊天开始时间:21:45:24.537000“

粗体的时间戳是receive方法启动时的时间戳。 “chat start”时间戳是调用chat\u message方法的时间。你知道吗

class MyConsumer(WebsocketConsumer):
    groups = ["my_group"]

    def connect(self):
        print("connected")
        self.accept()

    def receive(self, text_data=None, bytes_data=None):
        ts = datetime.now().strftime("%H:%M:%S.%f")

        self.send(text_data=json.dumps("1. Self send {}".format(ts)))

        text_data = "2. {} first group call".format(ts)
        async_to_sync(self.channel_layer.group_send)(
            "my_group",
            {
                "type": "chat.message",
                "text": text_data,
            },
        )
        text_data = self.long_running_function(ts)
        async_to_sync(self.channel_layer.group_send)(
            "my_group",
            {
                "type": "chat.message",
                "text": text_data,
            },
        )

    def disconnect(self, close_code):
        print("disconnected")
        async_to_sync(self.channel_layer.group_discard)("my_group", self.channel_name)

    def chat_message(self, event):
        chat_msg_start_time = datetime.now().strftime("%H:%M:%S.%f")
        text_data = "{} chat start: {}".format(event["text"], chat_msg_start_time)
        self.send(text_data=json.dumps(text_data))

    def long_running_function(self, ts):
        start_time = datetime.now().strftime("%H:%M:%S.%f")
        time.sleep(2)
        end_time = datetime.now().strftime("%H:%M:%S.%f")
        msg = "3. {} second group send lrf start_time: {} lrf end_time: {}".format(ts, start_time, end_time)
        return msg

Tags: 方法textselfsendmessagedataasynctime