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
相关推荐
时间海8711 小时前
前端表单如何防止重复提交
后端
稀土蚯蚓1 小时前
OLAP 分析引擎:StarRocks、Doris、ES、ClickHouse,存算分离、列式存储 Parquet
后端
Norna1 小时前
Git 给路径加了引号,这个文件就从 review 里消失了
python
旋律4141 小时前
序列化与反序列化
后端
wuyk5551 小时前
Python办公自动化-第04讲-批量新建Excel
开发语言·python·excel
wuyk5551 小时前
Spider-第20讲-综合实战可上线爬虫
大数据·爬虫·python·elasticsearch
JonaHu2 小时前
关键词排名突然消失?用 Python、SQLite 和 SERP API 搭一套可解释的 SEO 监控
python·sqlite·seo·serp api
TSuperman3 小时前
一次由高危漏洞引发的 Nginx 1.30.7 跨发行版安全升级实战
后端
静水深码3 小时前
文生图提示词的工程师写法:把玄学话术拆成结构化模板
人工智能·后端·代码规范
prince_zxill3 小时前
把 17 个散文件装进一个文件夹:拆解 claude-plugins-official 的插件打包术(47,413 Star 实测)
python·github·agent·mcp·claude code