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
相关推荐
码途行者7 小时前
每天10分钟学Go:第17课 接口interface-只规定“能做什么“,不管它是什么
开发语言·后端·golang
timeDifference₇9 小时前
Python Vibe Coding实操实验报告
开发语言·jvm·python
geovindu10 小时前
python:DecisionTree
开发语言·后端·python·算法
Cosolar10 小时前
从 Java 21 升到 25、Spring Boot 3 升 4:一次可复现的迁移踩坑实录
java·后端·面试
怒放的生命199111 小时前
代码知识库 RAG 问答系统 —— 从 0 到 1 实现教程
python·状态模式·fastapi·全栈开发·ai agent应用开发
geovindu11 小时前
python: Decision Tree Regressor
开发语言·后端·python·算法·决策树
码事漫谈11 小时前
黄仁勋的来时路
后端
bai27312 小时前
path.join('C:\a', '\b') 给我 C:\a\b,path.resolve 给 C:\b:Windows 上 51 行路径实测
javascript·后端
hackhase12 小时前
Django 多表数据整合:7 张异构表如何收敛成 4 类页面
后端·mysql
fengkai454512 小时前
Python运维
运维·python·监控·psutil·ipy