django channels
django channels 是django支持websocket的一个模块。
1. 安装
1
|
pip3 install channels |
2. 快速上手
2.1 在settings中添加配置
1 2 3 4 5 6 7 8 9 10 11 | INSTALLED_APPS = [ 'django.contrib.admin' , 'django.contrib.auth' , 'django.contrib.contenttypes' , 'django.contrib.sessions' , 'django.contrib.messages' , 'django.contrib.staticfiles' , 'channels' , ] 注册channels的app |
#配置路径
ASGI_APPLICATION = "django_channels_demo.routing.application"
2.2 创建websocket应用和路由
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | #!/usr/bin/env python # -*- coding:utf-8 -*- from channels.routing import ProtocolTypeRouter, URLRouter from django.conf.urls import url from chat import consumers application = ProtocolTypeRouter({ 'websocket' : URLRouter([ url(r '^chat/$' , consumers.ChatConsumer), ]) }) 应用和路由 |
2.3 编写处理websocket逻辑业务
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | #!/usr/bin/env python # -*- coding:utf-8 -*- from channels.generic.websocket import WebsocketConsumer from channels.exceptions import StopConsumer class ChatConsumer(WebsocketConsumer): def websocket_connect( self , message): self .accept() def websocket_receive( self , message): print ( '接收到消息' , message) self .send(text_data = '收到了' ) def websocket_disconnect( self , message): print ( '客户端断开连接了' ) raise StopConsumer() 示例一 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | #!/usr/bin/env python # -*- coding:utf-8 -*- from channels.generic.websocket import WebsocketConsumer from channels.exceptions import StopConsumer class SimpleChatConsumer(WebsocketConsumer): def connect( self ): self .accept() def receive( self , text_data = None , bytes_data = None ): self .send(text_data) # 主动断开连接 # self.close() def disconnect( self , code): print ( '客户端要断开了' ) 示例二 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 | #!/usr/bin/env python # -*- coding:utf-8 -*- from channels.generic.websocket import WebsocketConsumer from channels.exceptions import StopConsumer CLIENTS = [] class ChatConsumer(WebsocketConsumer): def connect( self ): self .accept() CLIENTS.append( self ) def receive( self , text_data = None , bytes_data = None ): for item in CLIENTS: item.send(text_data) # 主动断开连接 # self.close() def disconnect( self , code): CLIENTS.remove( self ) 示例三 |
3. channel layer
基于内存的channel layer
CHANNEL_LAYERS = { "default": { "BACKEND": "channels.layers.InMemoryChannelLayer", } }
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | from channels.generic.websocket import WebsocketConsumer from asgiref.sync import async_to_sync class ChatConsumer(WebsocketConsumer): def connect( self ): async_to_sync( self .channel_layer.group_add)( 'x1' , self .channel_name) self .accept() def receive( self , text_data = None , bytes_data = None ): async_to_sync( self .channel_layer.group_send)( 'x1' , { 'type' : 'xxx.ooo' , 'message' : text_data }) def xxx_ooo( self , event): message = event[ 'message' ] self .send(message) def disconnect( self , code): async_to_sync( self .channel_layer.group_discard)( 'x1' , self .channel_name) 业务处理 |
基于 redis的channel layer
1 | pip3 install channels - redis |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 | CHANNEL_LAYERS = { "default" : { "BACKEND" : "channels_redis.core.RedisChannelLayer" , "CONFIG" : { "hosts" : [( '10.211.55.25' , 6379 )] }, }, } CHANNEL_LAYERS = { 'default' : { 'BACKEND' : 'channels_redis.core.RedisChannelLayer' , 'CONFIG' : { "hosts" : [ "redis://10.211.55.25:6379/1" ],}, }, } CHANNEL_LAYERS = { 'default' : { 'BACKEND' : 'channels_redis.core.RedisChannelLayer' , 'CONFIG' : { "hosts" : [( '10.211.55.25' , 6379 )],},}, } CHANNEL_LAYERS = { "default" : { "BACKEND" : "channels_redis.core.RedisChannelLayer" , "CONFIG" : { "hosts" : [ "redis://:password@10.211.55.25:6379/0" ], "symmetric_encryption_keys" : [SECRET_KEY], }, }, } 配置 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | from channels.generic.websocket import WebsocketConsumer from asgiref.sync import async_to_sync class ChatConsumer(WebsocketConsumer): def connect( self ): async_to_sync( self .channel_layer.group_add)( 'x1' , self .channel_name) self .accept() def receive( self , text_data = None , bytes_data = None ): async_to_sync( self .channel_layer.group_send)( 'x1' , { 'type' : 'xxx.ooo' , 'message' : text_data }) def xxx_ooo( self , event): message = event[ 'message' ] self .send(message) def disconnect( self , code): async_to_sync( self .channel_layer.group_discard)( 'x1' , self .channel_name) 业务逻辑 |
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY