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
相关推荐
神奇元创23 分钟前
商用级光路加速卡:大模型推理的极速落地方案
python·神经网络·fpga开发·dsp开发
运筹vivo@36 分钟前
Python ContextVar 底层机制与内存模型拆解
前端·数据库·python
大白菜和MySQL38 分钟前
java应用排查高线程
java·python
嵌入式协会20240721 小时前
(已解决)MinIO python 获取预签名出现forbidden、errornetwork等错误
java·开发语言·python
宸丶一1 小时前
Day 14:任务追踪 - 让 Agent 拥有项目管理能力
开发语言·python
skylar01 小时前
小白1分钟安装flash-attn
开发语言·python
JustNow_Man1 小时前
psmux快捷键
人工智能·python
默子昂2 小时前
ollama 自定义ui
开发语言·python·ui
abcy0712132 小时前
Python中使用FastAPI和HDFS进行异步文件上传
python·fastapi