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
相关推荐
ynchyong13 分钟前
SQLAlchemy 更新操作:values() 与 ordered_values() 的隐藏差异
python·sqlalchemy·update·values·ordered_values
JaguarJack22 分钟前
Whim 是什么?一门把 PHP 被否决的设想真跑起来的实验语言
后端·php·服务端
statistican_ABin27 分钟前
中国互联网与数字生活分析报告—基于1990-2023年世界银行互联网数据的多维度分析
python
明月_清风33 分钟前
MHS:AI Agent 开始连接物理世界
人工智能·后端·网络协议
“AI国潮设计-小江”39 分钟前
【Python/SDXL实战】潮汕国潮IP视觉落地:普宁美食猫IP & 创意甜品设计(附ComfyUI工作流思路)
开发语言·人工智能·python·prompt·aigc
ssshooter42 分钟前
Node.js 天生就是异步的,为什么还要消息队列?
javascript·后端·面试
福兮说1 小时前
Gin 项目里的错误处理:让 Controller 不必知道错误是怎么来的
后端·go·gin·架构设计
Allen_LVyingbo1 小时前
医疗人工智能项目全生命周期管理系统:监管知识建模、工程实现与实证评估(下)
大数据·数据库·人工智能·python·自然语言处理·自动化
n8n1 小时前
Spring AI Alibaba Graph 实战:用图编排复杂业务,替代硬编码,支持分支、并行与人工确认
后端
wuhuhuan1 小时前
Case Generator 平台升级
python·测试工具·自动化