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
相关推荐
张高兴16 分钟前
张高兴的 Hailo-10 开发指南:(二)使用 LangChain 搭建本地大模型 RAG 问答应用
python·边缘计算·hailo
财经资讯数据_灵砚智能30 分钟前
基于全球经济类多源新闻的NLP情感分析与数据可视化(日间)2026年6月6日
大数据·人工智能·python·ai·信息可视化·自然语言处理·灵砚智能
Land032941 分钟前
Python + RPA 双引擎实战:从手写脚本到可交付自动化应用的完整链路
python·自动化·rpa
好家伙VCC1 小时前
区块链双向支付通道实战:从签名到结算
java·后端·区块链·asp.net
菜到离谱但坚持1 小时前
【小白零基础】RAG+LangChain 搭建私有知识库问答系统(完整可运行代码+超详细教程+避坑指南)
python·langchain·rag
ss2731 小时前
【入门OJ题解】分苹果问题(Python/Java/C 实现)
java·c语言·python
IsJunJianXin1 小时前
谷歌搜索cookie NID逆向生成
开发语言·python·google搜索·sgss·nid-cookie·算法生成nid·google-cookie
暗夜猎手-大魔王1 小时前
转载--Hermes Agent 11 | 智能审批与平台化安全:当 AI 来守护 AI
人工智能·python·安全
AIFQuant1 小时前
量化私募回测系统:高质量股票/外汇历史数据 API 选型与接入
python·websocket·金融·ai量化
Mr.Daozhi1 小时前
Playwright实战:抓取Meta Ad Library动态页面的三级降级策略
爬虫·python·自动化·playwright·meta广告