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
相关推荐
谭光志7 小时前
Vibe Coding 时代,程序员该何去何从
前端·后端·ai编程
GoGeekBaird7 小时前
我用 BeeWeave 跑完了一次完整写作闭环
后端·github
闻道且行之8 小时前
TurboOCR:基于PP-OCRv6的极速Windows离线OCR工具,深度解析3.4GB依赖背后的技术架构
c++·人工智能·python·qt·机器学习·ocr
仿生狮子9 小时前
别再说“全栈”了,AI 时代团队只认这 5 种人
前端·人工智能·后端
许彰午9 小时前
95_Python内存管理与垃圾回收
开发语言·python
骄阳如火9 小时前
Python 性能深度剖析:从“被诟病的慢”到“Rust 重塑”的拐点
python
满怀冰雪10 小时前
03-第一个 Paddle 程序:Tensor 创建、计算与设备管理
人工智能·python·paddle
CClaris10 小时前
大模型量化从0到1(九):用 llama.cpp 把模型转成 GGUF 并跑本地推理
人工智能·pytorch·python·深度学习·llama
学编程的小虎10 小时前
SenseVoice微调
人工智能·python·自然语言处理
诸葛说抛光11 小时前
国内大型汽车改装展览会定展 佛山改装 佛山汽车赛事
python·汽车