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 分钟前
Skill原理及国内大模型实践
人工智能·python
IT管理圈28 分钟前
Cursor Rules 实战指南—让AI按你的规矩写代码
python
Java后端的Ai之路32 分钟前
微调模型成本太高,用RAG技术,低成本实现AI升级
开发语言·人工智能·python·rag·ai升级
楚兴39 分钟前
Go + Eino 构建 AI Agent(一):Hello LLM
人工智能·后端
喵手41 分钟前
Python爬虫实战:从零构建书籍价格情报数据库(附CSV导出 + SQLite持久化存储)!
爬虫·python·爬虫实战·零基础python爬虫教学·csv导出·构建书籍价格情报·书籍价格采集
勾股导航44 分钟前
蚁群优化算法
人工智能·pytorch·python
小锋java12341 小时前
分享一套【优质Python源码】基于Python的Django学生就业管理系统
python
一个处女座的程序猿O(∩_∩)O1 小时前
Python字典详解
开发语言·python
一个处女座的程序猿O(∩_∩)O1 小时前
Go语言Map值不可寻址深度解析:原理、影响与解决方案
开发语言·后端·golang
List<String> error_P1 小时前
蓝桥杯基础知识点:模拟-数位操作类题目
python·算法·蓝桥杯