django channels中 在customer之外使用channel 您所在的位置:网站首页 channel意思 django channels中 在customer之外使用channel

django channels中 在customer之外使用channel

2023-08-25 10:09| 来源: 网络整理| 查看: 265

channels文档中有Using Outside Of Consumers,介绍了如何在消费者类外使用channel_layer

from channels.layers import get_channel_layer from asgiref.sync import async_to_sync channel_layer = get_channel_layer() async_to_sync(channel_layer.group_send)("chat", {"type": "chat.force_disconnect"})

这里的type一度让我很迷茫,之前在consumers类中,理解的是该类中的一个自定义的函数,但是都out of consumers 怎么还用consumers类中的函数呢..

# 这里附上一般的consumer类 class ChatConsumer(WebsocketConsumer): def connect(self): self.room_group_name = "test" async_to_sync(self.channel_layer.group_add)(self.room_group_name, self.channel_name) self.accept() def disconnect(self, close_code): async_to_sync(self.channel_layer.group_discard)( self.room_group_name, self.channel_name ) def receive(self, text_data): text_data_json = json.loads(text_data) message = text_data_json['message'] async_to_sync(self.channel_layer.group_send)( self.room_group_name, { 'type': 'chat_message', # 这里的type 实际上就是 下面的chat_message自定义函数 'message': message } ) def chat_message(self, event): message = event['message'] # Send message to WebSocket self.send(text_data=json.dumps({ 'message': "已发送调试信息,请耐心等待回复" }))

后来我在某位不知名大佬的博客下提问后,大佬给我的回答让我走出了胡同,我提问的那篇博客 ,他用的评论插件,需要翻墙后才能看到,我这里就贴张图吧 大佬的解释 看了他的解释,豁然开朗~~ 实际上get_channel_layer() 函数获得的是当前的websocket连接所对应的consumer类对象的channel_layer,因此,可以在consumer类中写的函数,在外面也能调用. 我写个示例,可以理解下:

# demo/consumers # consumer类 class ChatConsumer(WebsocketConsumer): def connect(self): self.room_group_name = "test" async_to_sync(self.channel_layer.group_add)(self.room_group_name, self.channel_name) self.accept() def disconnect(self, close_code): async_to_sync(self.channel_layer.group_discard)( self.room_group_name, self.channel_name ) def receive(self, text_data): text_data_json = json.loads(text_data) message = text_data_json['message'] async_to_sync(self.channel_layer.group_send)( self.room_group_name, { 'type': 'chat_message', # 这里的type 实际上就是 下面的chat_message自定义函数 'message': message } ) def chat_message(self, event): message = event['message'] # Send message to WebSocket self.send(text_data=json.dumps({ 'message': "已发送调试信息,请耐心等待回复" })) def send_message(self, event): message = event['message'] # Send message to WebSocket self.send(text_data=json.dumps({ 'message': "啦啦啦~~" })) # demo/outofconsumer from channels.layers import get_channel_layer channel_layer = get_channel_layer() group_name='test' # channel 内部会自动把 . 转化成 _ async_to_sync(channel_layer.group_send)(group_name, {"type": "send.message", "message": payload['message']})

这样在调用outofconsumer时 就会给属于该consumer的websocket连接发送啦啦啦~~

本文纯属个人记录,如果能帮到你,记得点赞~



【本文地址】

公司简介

联系我们

今日新闻

    推荐新闻

    专题文章
      CopyRight 2018-2019 实验室设备网 版权所有