Django使用WebSocket

django channels 是django支持websocket的一个模块。

1安装.

|-------------------------|
| pip3 install channels |

2.在settings中添加配置

python 复制代码
INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'channels',
]

ASGI_APPLICATION = "django_channels_demo.routing.application"

3.创建websocket应用和路由

python 复制代码
#!/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),
    ])
})

4.编写处理websocket逻辑业务

python 复制代码
#!/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()

5.启动:

python 复制代码
daphne -b 0.0.0.0 -p xxxx xxxx.asgi:application
相关推荐
小二·2 分钟前
Python Web 开发进阶实战:混沌工程初探 —— 主动注入故障,构建高韧性系统
开发语言·前端·python
Lkygo5 分钟前
LlamaIndex使用指南
linux·开发语言·python·llama
小二·7 分钟前
Python Web 开发进阶实战:低代码平台集成 —— 可视化表单构建器 + 工作流引擎实战
前端·python·低代码
Wise玩转AI9 分钟前
团队管理:AI编码工具盛行下,如何防范设计能力退化与知识浅薄化?
python·ai编程·ai智能体·开发范式
赵谨言1 小时前
Python串口的三相交流电机控制系统研究
大数据·开发语言·经验分享·python
座山雕~1 小时前
Springboot
android·spring boot·后端
鹿角片ljp1 小时前
Engram 论文精读:用条件记忆模块重塑稀疏大模型
python·自然语言处理·nlp
Blossom.1182 小时前
AI Agent的长期记忆革命:基于向量遗忘曲线的动态压缩系统
运维·人工智能·python·深度学习·自动化·prompt·知识图谱
love530love2 小时前
ComfyUI Hunyuan-3D-2 插件安装问题解决方案
人工智能·windows·python·3d·comfyui·hunyuan-3d-2·pygit2
我是一只小青蛙8882 小时前
Python Pandas 从入门到精通全指南
python