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
相关推荐
Fluxproxy1 天前
Python请求玄学根治:彻底解决脚本间歇性超时、断连、假死问题
网络·python·安全
青 春 记 忆1 天前
零基础入门Python15|关联、聚合、索引与事务:订单数据库
开发语言·python·后端开发
东风破_1 天前
NestJS CRUD 实战:用 Todos 模块打通 Controller-Service-Module 三层
后端
东风破_1 天前
NestJS 框架入门:从工厂模式到模块化架构
后端
灯澜忆梦1 天前
【基于GO的Web开发4】html/template 模板语法
后端·golang·html
一只叫煤球的猫1 天前
Spring AI 2.0 源码解析(三):ChatClient 的 Fluent API 如何构建请求?
java·后端·面试
qq_513728041 天前
Alert 原生弹窗处理
python
掘金者阿豪1 天前
数据库迁移工具选了半年,最后发现决策的起点错了
后端
李可以量化1 天前
Redis 从了解到精通(三)上:量化交易场景下的数据备份与安全配置
redis·python·安全·qmt·ptrade