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·算法·afsim智能体训练·评估算法·鲁棒性算法·泛化测试算法
SummerJokes23 分钟前
Java 集合 List 全套实验|从基础增删改查到实体类存储
java·python·list
想不到一个好的ID1 小时前
G1 垃圾回收器
后端
车软学堂1 小时前
Docker在隔离什么:namespace、cgroup、chroot三道墙
linux·python·docker·容器·车载系统·汽车·测试用例
ZhengEnCi1 小时前
模型配置页怎么做:多模型备用链自动切换,API Key 加密存储只显示掩码
后端·llm·ai编程
zhanghongyi_cpp2 小时前
第4章 学习自测
python·学习
李松桃2 小时前
Python爬虫基础
开发语言·爬虫·python·get请求使用方法·post请求使用方法
weixin_307779132 小时前
Python用正则把 SQL 关键字整词匹配后转成小写
开发语言·python·sql·算法
Mk598782 小时前
一人公司用 FastAPI+Vue3 搭工作台,我把 5 个阶段跑通了
vue.js·后端
Rain的Java大神之路2 小时前
Java后端用Vue3+TS独立闭环之后,MyBatis-Plus该退到哪一层?聊聊2026全栈效能的责任边界
java·后端·ai编程