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
相关推荐
天使day22 分钟前
FastAPI快速入门
python·fastapi
databook27 分钟前
用相关性分析消除“冗余特征”
python·机器学习·scikit-learn
SomeB1oody1 小时前
【RustyML入门】1.0. 快速上手
开发语言·后端·机器学习·rust·教程
幻想时空1 小时前
地图数据采集
python
梦想不只是梦与想1 小时前
Python 中的类型判断方法
python·type·isinstance
史呆芬1 小时前
分布式事务实战:微服务跨服务数据一致性解决方案
java·后端·spring cloud
犀利豆2 小时前
Claude code tools 研究系列(二)EnterPlanMode
人工智能·后端
alphaTao2 小时前
LeetCode 每日一题 2026/7/27-2026/8/2
python·算法·leetcode