Used in Django views, channels channel layer

foreword

Sometimes, I need to push the data generated in the Django view to the user through websocket, what should I do? There is an ASGI framework supporting Django to implement websocket, but there are few introductions on the official website and other places.

1 Preparations

Install Django and channels

Install redis as a data cache

sudo apt-get install redis-server

Configure the redis database in the settings of Django, and refer to the official documentation of channels

2 What is the channel layer, and what is the relationship between a group and the channel layer?

Diagram of the relationship between channel and group
Through personal practice, I realized the structure of the above picture. The so-called channel layer is like a very thick wire, used to transmit information. The ws connection (channel1 or channel2) established by a user is like a thin metal wire in the wire (assuming that the wires are all wrapped by insulators). If it's just you and the server, a small channel is enough. However,
if many people need to share communication information, then you need to create a group. It is to tie thin metal wires one by one and insert them into the group to realize the sharing of information.

3 Practice Test

in view

import channels.layers
from asgiref.sync import async_to_sync

channel_layer = channels.layers.get_channel_layer() # 获取频道层
async_to_sync(channel_layer.group_send)(group_name, payload_dict) # 第一个参数写组名,第二个是一个字典
# payload_dict必填项
payload_dict={
    
    
            'type': 'receive', # 指定consumer(消费者)类接受消息的函数,receive是函数名
            'message': '消息'
        }

consumer

from asgiref.sync import async_to_sync
from channels.generic.websocket import WebsocketConsumer

class ResultConsumer(WebsocketConsumer):
    def connect(self):
        # Join room group
        async_to_sync(self.channel_layer.group_add)(
            group_name,
            self.channel_name
        )
        self.accept()
        
    def disconnect(self, code):
        async_to_sync(self.channel_layer.group_discard)(
            group_name,
            self.channel_name
        )
        
    def receive(self, text_data=None, bytes_data=None):
        message = text_data['message']
		# 相应的逻辑自己实现吧            

4 bye

If you have any questions, you can send a private message.

Guess you like

Origin blog.csdn.net/xin_IT_able/article/details/103177034