django channels 是django支持websocket的一个模块。

1. 安装

1

pip3 install channels

2. 快速上手

2.1 在settings中添加配置

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"

2.2 创建websocket应用和路由

#!/usr/bin/env python
# -*- coding:utf-8 -*-
from channels.routing import ProtocolTypeRouter, URLRouter
from django.conf.urls import url
from chat import consumersapplication = ProtocolTypeRouter({'websocket': URLRouter([url(r'^chat/$', consumers.ChatConsumer),])
})

2.3 编写处理websocket逻辑业务

#!/usr/bin/env python
# -*- coding:utf-8 -*-
from channels.generic.websocket import WebsocketConsumer
from channels.exceptions import StopConsumerclass 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()

示例二

#!/usr/bin/env python
# -*- coding:utf-8 -*-
from channels.generic.websocket import WebsocketConsumer
from channels.exceptions import StopConsumerclass SimpleChatConsumer(WebsocketConsumer):def connect(self):self.accept()def receive(self, text_data=None, bytes_data=None):self.send(text_data)# 主动断开连接# self.close()def disconnect(self, code):print('客户端要断开了')

示例三

#!/usr/bin/env python
# -*- coding:utf-8 -*-
from channels.generic.websocket import WebsocketConsumer
from channels.exceptions import StopConsumerCLIENTS = []class ChatConsumer(WebsocketConsumer):def connect(self):self.accept()CLIENTS.append(self)def receive(self, text_data=None, bytes_data=None):for item in CLIENTS:item.send(text_data)# 主动断开连接# self.close()def disconnect(self, code):CLIENTS.remove(self)

3. channel layer

基于内存的channel layer

配置

CHANNEL_LAYERS = {"default": {"BACKEND": "channels.layers.InMemoryChannelLayer",}
}

配置

from channels.generic.websocket import WebsocketConsumer
from asgiref.sync import async_to_syncclass ChatConsumer(WebsocketConsumer):def connect(self):async_to_sync(self.channel_layer.group_add)('x1', self.channel_name)self.accept()def receive(self, text_data=None, bytes_data=None):async_to_sync(self.channel_layer.group_send)('x1', {'type': 'xxx.ooo','message': text_data})def xxx_ooo(self, event):message = event['message']self.send(message)def disconnect(self, code):async_to_sync(self.channel_layer.group_discard)('x1', self.channel_name)

业务处理

基于 redis的channel layer

1

pip3 install channels-redis

CHANNEL_LAYERS = {"default": {"BACKEND": "channels_redis.core.RedisChannelLayer","CONFIG": {"hosts": [('10.211.55.25', 6379)]},},
}CHANNEL_LAYERS = {'default': {'BACKEND': 'channels_redis.core.RedisChannelLayer','CONFIG': {"hosts": ["redis://10.211.55.25:6379/1"],},},
}CHANNEL_LAYERS = {'default': {'BACKEND': 'channels_redis.core.RedisChannelLayer','CONFIG': {"hosts": [('10.211.55.25', 6379)],},},
}CHANNEL_LAYERS = {"default": {"BACKEND": "channels_redis.core.RedisChannelLayer","CONFIG": {"hosts": ["redis://:password@10.211.55.25:6379/0"],"symmetric_encryption_keys": [SECRET_KEY],},},
}
from channels.generic.websocket import WebsocketConsumer
from asgiref.sync import async_to_syncclass ChatConsumer(WebsocketConsumer):def connect(self):async_to_sync(self.channel_layer.group_add)('x1', self.channel_name)self.accept()def receive(self, text_data=None, bytes_data=None):async_to_sync(self.channel_layer.group_send)('x1', {'type': 'xxx.ooo','message': text_data})def xxx_ooo(self, event):message = event['message']self.send(message)def disconnect(self, code):async_to_sync(self.channel_layer.group_discard)('x1', self.channel_name)

django channels相关推荐

  1. Django Channels 入门指南

    http://www.oschina.NET/translate/in_deep_with_django_channels_the_future_of_real_time_apps_in_django ...

  2. django channels

    一直都是用HTTP请求糊里糊涂的实现了一次请求,一次响应.最近尝试用Django这种框架实现websocket,用的是Django channels,结合官网给的例子,实现了日志动态展示到页面.源码地 ...

  3. Django channels摄像头实时视频传输

    Django channels摄像头实时视频传输(视屏能传别的当然也能传拉) 前言 不想看我瞎扯可以直接跳到这 服务端 步骤 解释 发送端 接收端 运行 前言 (网上绝大多数博客都是发送端或者接收端同 ...

  4. Python+Django+channels实现websocket

    Python+Django+channels实现websocket 前言 公司需要实现一个长连接,用的Python的Django框架.研究了很长时间,发现Django+channels可以实现webs ...

  5. Django Channels配置

    channels 4.0之后默认不带Daphne服务器了.解决方案可以有两种: 1.指定channels的版本为3.x: 2.安装时使用pip3 install -U channels["d ...

  6. Django Channels 原理

    Django Channels 是一个为 Django 提供异步扩展的库,通常主要用来提供 WebSocket 支持和后台任务. 原理 它的原理是将 Django 分为 2 种进程类型: 一个用于处理 ...

  7. 基于Django channels 与 YOLO v8 搭建 <实时跟踪与统计系统>

    文章大纲 0. 简介 系统Demo 前序文章 1. 系统架构:基于分层结构.组件解耦的<实时跟踪与统计系统> 2. YOLOv8 3. 目标跟踪与计数:SORT ( Simple Onli ...

  8. Python+Django+Channels之Consumers(用户)

    Consumers 因为建立Channels最底层的解释接口是ASGI,被用来连接复杂应用的操作接口 当然你也可以忽略consumers而使用其他Channels部分,像routing,session ...

  9. django channels socket通信实现

    我们知道python有socket包可以直接实现socket通信. 但在使用django时,不太适用于socket的方式与前端交互,对此django有channels来很好的支持socket通信.参考 ...

最新文章

  1. ImageNet十年,AI数据标注如何蓬勃发展?
  2. 部署war包到阿里云liunx的tomcat时报错:zip END header not found
  3. DevOps 的发展史
  4. (28)SpringBoot启动时的Banner设置【从零开始学Spring Boot】
  5. 爬虫Selenium报错“cannot find Chrome binary“解决方案
  6. (四)DOM对象和jQuery对象
  7. [导入]C#中TextBox只能输入数字的代码
  8. C++ —— 初识C++
  9. Hadoop伪分布式搭建(本人新手,欢迎大家多多指导和关照)
  10. Cannot resolve plugin org.apache.maven.plugins:xxxx
  11. R6900P/R7000P 梅林固件
  12. 设计模式 单例模式解决线程安全问题
  13. 抛弃手册,开启TongWeb+TongLINK/Q的开发方式
  14. 网络变压器 网络变压器设计线路分类及其设计目的和侧重点
  15. CPU处理器Intel Xeon Skylake 6148(2.4 GHz)性能评测
  16. 文案怎么写,才会更有画面感,告诉你2个方法(三)
  17. 实用:python中字典的扁平化(flat)
  18. 华为S5300系列交换机V200R001SPH027升级补丁
  19. 解决前端导出excel文件,打开为乱码
  20. UMLChina建模竞赛第3赛季第3轮(《人月神话》专场)

热门文章

  1. 纯CSS卡通狮子样式代码
  2. hessian c java_hessian 使用异常处理
  3. 使用Python获取股票数据(csv文件)
  4. Java游戏服务器开发之二--导航帖
  5. 《东周列国志》第九十四回 冯谖弹铗客孟尝 齐王纠兵伐桀宋
  6. 当渡鸦已成往事 吕骋开启AI“皮克斯梦”
  7. 关于WiFiBT模组的EFuse说明
  8. JS 获取url上的参数
  9. Python3(综合练习 绘出多个颜色不同的同心圆)
  10. 分享快速查询快递物流,并查看每个快递物流详情的方式