如何在通道中同步 AsyncWebsocketConsumer 中的函数?

问题描述

我在频道中使用 AsyncWebsocketConsumer 来创建基本的群组消息传递 保存在数据库或任何其他进程的数据不应发送到 WebSocket 工作正常,但是当我尝试在套接字打开函数获取所有以前的消息时,它不是将数据发送到套接字而是检索数据...

基本上,它并行运行两个进程,所以我需要使用syncWebsocketConsumer并使用async和await吗?或者有什么东西可以使异步消费者中的一些事情同步?

class ChatConsumer(AsyncWebsocketConsumer):
     ...
     async def receive(self,text_data):
        text_data_json = json.loads(text_data)
        message = text_data_json['message']
        user = text_data_json['user']
        print(text_data_json['type'])
        #using init_messages for fetching
        await self.channel_layer.group_send(
            self.room_group_name,{
                'type': text_data_json['type'],'message':message,'user': text_data_json['user']
            }
        )
        print("sended")

     async def init_messages(self,event):
        messages = await sync_to_async(get_last_10_messages)(self.room_name)
        print(messages)
        messages = self.parse_messages(messages)
        self.send(text_data=json.dumps({
            'messages':messages,}))

parse_messages 只是给出字典

在房间.html

chatSocket.onopen = function(e){
                    chatSocket.send(JSON.stringify({
                        'type': "init_messages",'message':"",'user': user_username,}));
                    console.log('for debug')
                }

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)