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
相关推荐
金銀銅鐵5 小时前
类实例里还有什么——putfield、getfield 与对象传递
java·jvm·后端
xurileidian5 小时前
第 24 篇 · 边玩边学Python · while 与死循环怎么退
服务器·前端·python
皮皮林5516 小时前
你还在使用 WebSocket 实现实时消息推送吗?
后端
有个傻瓜6 小时前
工具调用参数每次都差一截:finish_reason=length 输出预算截断的排错复盘与四种分诊实测
python·故障排查·ai agent·大模型应用开发·function calling
码事漫谈6 小时前
token账单到底要怎么看
后端
zhanghongyi_cpp6 小时前
第5章 学习自测
python·学习
Cosolar7 小时前
当 Harness 标准化后,工程师还剩什么?
人工智能·后端·agent
打工仔折腾 AI7 小时前
L3 静态源码取证|工程评测:python-oracledb 驱动评估中的样本偏差陷阱
开发语言·人工智能·后端·python·性能优化
stark张宇8 小时前
分布式事务方案设计与选型思考:消息队列
后端
IvanCodes8 小时前
LangChain(15):LangSmith 应用评估与回归测试
python·langchain·agent