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
相关推荐
庚昀◟12 小时前
ClaudeCode安装教程,基础使用、进阶推荐
人工智能·python·ai
楼田莉子12 小时前
C++17新特性:结构化绑定/inline变量/if相关的变化
c++·后端·学习
deephub12 小时前
告别脆弱的单体应用,用多智能体网络构建稳定的生产力工具
人工智能·python·大语言模型·多智能体
烟雨江南aabb12 小时前
Python第六弹:python爬虫篇:什么是爬虫
开发语言·爬虫·python
MomentYY12 小时前
第 1 篇:Agent 到底是什么?别被概念唬住了
人工智能·python·agent
无限进步_12 小时前
【C++】C++11的类功能增强与STL变化
java·前端·数据结构·c++·后端·算法
字节跳动数据库12 小时前
TRAE × 火山引擎 Supabase:为你的 AI 应用装上“数据引擎”
人工智能·后端
Python大数据分析@13 小时前
对你而言, Vibe Coding 的乐趣是什么?
python
WL_Aurora13 小时前
Python 算法基础篇之排序算法(一):冒泡、选择、插入
python·算法·排序算法
龙腾AI白云13 小时前
中国人工智能培训网—AI系列录播课
python·beautifulsoup