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 分钟前
当对话模型遇上向量模型,vllm production stack 又该如何应对?
后端
传奇开心果编程28 分钟前
【springboot基础语法学与练】第 1 课:从零开始
java·spring boot·后端·学习
Bruce_Liuxiaowei32 分钟前
Python 实例赋值遮蔽类属性:一个从不报错的静默陷阱
开发语言·python·语法糖
IT_陈寒37 分钟前
Java线程池用错参数,我的服务居然悄悄崩溃了
前端·人工智能·后端
做运维的阿瑞40 分钟前
Python 标准库汇总:分类速览与常用模块清单
linux·运维·python
why-geo1 小时前
Hermes Agent 与 Python 的会产生什么样的碰撞
人工智能·python·ai编程
光影少年1 小时前
Express 中间件原理
后端·node.js·express
正经教主1 小时前
【FDE系列】阶段2:Day 29:FastAPI 进阶 — Pydantic 模型与完整 CRUD 实战
人工智能·python·fde
gCode Teacher 格码致知1 小时前
Pandas教学-6:coerce详解
python·pandas
梦在远山后1 小时前
Electron 与 FastAPI 如何完成流式 Agent 对话
python·langchain·agent