微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

如何解决如何在通道中同步 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 举报,一经查实,本站将立刻删除。