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
相关推荐
辣椒思密达24 分钟前
Python公开数据采集实战:如何解决请求高频拦截与Session会话中断问题
开发语言·python
Albart5751 小时前
Python 实战教程:用 30 分钟学会解决真实问题
开发语言·python
小蜜蜂dry1 小时前
nestjs实战-权限二:角色模块
前端·后端·nestjs
默默且听风1 小时前
Ubuntu 22 环境下 VS Code Codex 插件无法打开的排查与修复记录
后端·ai编程·vibecoding
小蜜蜂dry1 小时前
nestjs实战-权限一: 菜单模块
前端·后端·nestjs
2301_773643621 小时前
ceph池
开发语言·ceph·python
极客笔记Jack2 小时前
Scanpy AnnData 对象深度解析:高效操作数据结构的10个技巧
python
BingoGo2 小时前
PHP 在领域驱动(DDD)设计中的核心实践
后端·php
颜酱2 小时前
LangChain调用向量模型,存入向量数据库
python·langchain
2501_928945522 小时前
七本性全面签名体系:从互递归类型到∞-范畴生成语法
python