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 闭包与装饰器:从入门到精通
开发语言·python·面试
老大白菜12 分钟前
Qwen3.8-27B 本地推理 + DeepSeek Harness 配置
python·qwen·deepseek·harness
SelectDB技术团队25 分钟前
腾讯音乐内容库 ES 替代:从 Elasticsearch 到 Apache Doris 统一搜索分析引擎实践
elasticsearch·django·apache doris
Code额35 分钟前
Python 连接 DeepSeek API,OpenAI 对话方式总结
后端·python·ai·ai编程
电化学仪器白超35 分钟前
MV-CS200-10UC相机参数配置
python·单片机·嵌入式硬件·数码相机·自动化·ltspice
星火102436 分钟前
【LangChain4j系列10】Guardrails 安全护栏
人工智能·后端
四千岁37 分钟前
稀疏向量BM25Retriever不支持中文怎么办?jieba来帮忙
前端·javascript·后端
用户69190268133939 分钟前
Docker基本概念
后端·docker·容器
颜进强41 分钟前
14 - OpenSpec 老页面改造骨架:定位 + 增量 + 回归三件套
前端·后端·ai编程
唐青枫42 分钟前
别只把 switch 当成多路 if:Zig 模式匹配、状态机与 Tagged Union 实战
后端