Python+Django+Channels之Consumers(用户)
Consumers
因为建立Channels最底层的解释接口是ASGI,被用来连接复杂应用的操作接口
当然你也可以忽略consumers而使用其他Channels部分,像routing,session等等
基础布局
consumers 的子类有
channels.consumer.AsyncConsumer
channels.consumer.SyncConsumer
SyncConsumer的一个基础例子
from channels.consumer import SyncConsumerclass EchoConsumer(SyncConsumer):def websocket_connect(self, event):self.send({"type": "websocket.accept",})def websocket_receive(self, event):self.send({"type": "websocket.send","text": event["text"],})
通过在ASGI设置,我们可以获取到信息。
self.send(event)可以将事件发送到客户端或是服务器
与AsyncConsumer相似,其他的处理方法也要有self.send
from channels.consumer import AsyncConsumerclass EchoConsumer(AsyncConsumer):async def websocket_connect(self, event):await self.send({"type": "websocket.accept",})async def websocket_receive(self, event):await self.send({"type": "websocket.send","text": event["text"],})
什么时候使用AsyncConsumer或SyncConsumer?
当你使用慢同步函数循环整个事件时使用AsymcConsumer,如果你到用Django的ORM模型就应该使用SyncConsumer。一般使用SyncConsumer为默认值。
Closing Consumers关闭用户
当已连接的consumer要关闭时,需要使用http.disconnect或websocket.disconnect
当结束时会触发channels.exceptions.StopConsumer
Channel Layers
Consumer通过使用Channel Layers来相互发送消息或广播消息
Scope领域、范围
Consumuer能够接收连接所在的范围的消息
scope["path"]
, the path on the request. (HTTP and WebSocket)scope["headers"]
, raw name/value header pairs from the request (HTTP and WebSocket)scope["method"]
, the method name used for the request. (HTTP)
WebSocketConsumer
这个包channels.generic.websocket.WebsocketConsumer是处理发送和接收消息。
from channels.generic.websocket import WebsocketConsumerclass MyConsumer(WebsocketConsumer):groups = ["broadcast"]def connect(self):# Called on connection.# To accept the connection call:self.accept()# Or accept the connection and specify a chosen subprotocol.# A list of subprotocols specified by the connecting client# will be available in self.scope['subprotocols']self.accept("subprotocol")# To reject the connection, call:self.close()def receive(self, text_data=None, bytes_data=None):# Called with either text_data or bytes_data for each frame# You can call:self.send(text_data="Hello world!")# Or, to send a binary frame:self.send(bytes_data="Hello world!")# Want to force-close the connection? Call:self.close()# Or add a custom WebSocket error code!self.close(code=4123)def disconnect(self, close_code):# Called when the socket closes
AsyncWebsocketConsumer
from channels.generic.websocket import AsyncWebsocketConsumerclass MyConsumer(AsyncWebsocketConsumer):groups = ["broadcast"]async def connect(self):# Called on connection.# To accept the connection call:await self.accept()# Or accept the connection and specify a chosen subprotocol.# A list of subprotocols specified by the connecting client# will be available in self.scope['subprotocols']await self.accept("subprotocol")# To reject the connection, call:await self.close()async def receive(self, text_data=None, bytes_data=None):# Called with either text_data or bytes_data for each frame# You can call:await self.send(text_data="Hello world!")# Or, to send a binary frame:await self.send(bytes_data="Hello world!")# Want to force-close the connection? Call:await self.close()# Or add a custom WebSocket error code!await self.close(code=4123)async def disconnect(self, close_code):# Called when the socket closes
AsyncHttpConsumer
from channels.generic.http import AsyncHttpConsumerclass BasicHttpConsumer(AsyncHttpConsumer):async def handle(self, body):await asyncio.sleep(10)await self.send_response(200, b"Your response bytes", headers=[(b"Content-Type", b"text/plain"),])
import json
from channels.generic.http import AsyncHttpConsumerclass LongPollConsumer(AsyncHttpConsumer):async def handle(self, body):await self.send_headers(headers=[(b"Content-Type", b"application/json"),])# Headers are only sent after the first body event.# Set "more_body" to tell the interface server to not# finish the response yet:await self.send_body(b"", more_body=True)async def chat_message(self, event):# Send JSON and finish the response:await self.send_body(json.dumps(event).encode("utf-8"))
from datetime import datetime
from channels.generic.http import AsyncHttpConsumerclass ServerSentEventsConsumer(AsyncHttpConsumer):async def handle(self, body):await self.send_headers(headers=[(b"Cache-Control", b"no-cache"),(b"Content-Type", b"text/event-stream"),(b"Transfer-Encoding", b"chunked"),])while True:payload = "data: %s\n\n" % datetime.now().isoformat()await self.send_body(payload.encode("utf-8"), more_body=True)await asyncio.sleep(1)
参考资料https://channels.readthedocs.io/en/stable/topics/consumers.html
Python+Django+Channels之Consumers(用户)相关推荐
- Python+Django+channels实现websocket
Python+Django+channels实现websocket 前言 公司需要实现一个长连接,用的Python的Django框架.研究了很长时间,发现Django+channels可以实现webs ...
- Python + Django 如何支撑了 7 亿月活用户的 Instagram?
PyCon 简介 PyCon 是全世界最大的以 Python 编程语言为主题的技术大会.大会由 Python 社区组织,每年举办一次.在大会上,来自世界各地的 Python 用户与核心开发者齐聚一堂, ...
- 如何在Python Django中处理用户身份验证
by Mohammed Subhan Khan 由Mohammed Subhan Khan 如何在Python Django中处理用户身份验证 (How to handle user authenti ...
- Python+django网页设计入门(19):创建新模型扩展自带用户表的字段
公众号送书活动火热进行中:新学期福利,送18本Python图书 ================== 前导课程: Python+django网页设计入门(18):自定义模板过滤器 Python+dja ...
- Python+django网页设计入门(4):用户登录与登录验证
技术要点: 1)实现用户登录,登录后跳转到指定页面 2)限定一个页面必须登录才能访问,否则自动跳转到登录页面 ===================== 首先,按照Python+django网页设计入 ...
- Python+Django+Mysql实现购物商城推荐系统 基于用户、项目的协同过滤推荐购物商城系统 网络购物推荐系统 代码实现 源代码下载
Python+Django+Mysql实现购物商城推荐系统(基于用户.项目的协同过滤推荐算法) 一.项目简介 1.开发工具和实现技术 pycharm2020professional版本,python3 ...
- Python+Django+Mysql实现在线音乐推荐系统 基于用户、项目、兴趣标签的协同过滤推荐在线音乐系统、用户兴趣标签推荐系统 代码实现 源代码下载
Python+Django+Mysql实现在线音乐推荐系统(基于用户.项目的协同过滤推荐算法) 一.项目简介 1.开发工具和实现技术 pycharm2020professional版本,python3 ...
- Python+Django+Mysql个性化图书推荐系统 图书在线推荐系统 基于用户、项目、内容的协同过滤推荐算法(带设计报告)
Python+Django+Mysql个性化图书推荐系统 图书在线推荐系统 基于用户.项目.内容的协同过滤推荐算法 WebBookRSM.Python python实现协同过滤推荐算法实现 源代码下载 ...
- Python+Django+Mysql实现在线电影推荐系统 基于用户、项目的协同过滤推荐在线电影系统 代码实现 源代码下载
Python+Django+Mysql实现在线电影推荐系统(基于用户.项目的协同过滤推荐算法) 一.项目简介 1.开发工具和实现技术 pycharm2020professional版本,python3 ...
最新文章
- 博士买房后发现被坑,于是写万字论文维权,网友:维权界的天花板...
- Compellent试用手记之二:系统连接
- C语言学习之分别用while、for 编写程序,计算1+2+3+......+100的值
- java reader_Java Reader reset()方法与示例
- html 修改按回退键的url,location.hash保存页面状态的技巧
- QDateTimeEdit使用
- 2018.12.11 区块链论文翻译
- redis学习笔记二
- html弹窗代码大全定时弹窗,js点击弹窗弹出表单框代码
- C Sharp编写缓和曲线计算应用程序
- Pandas 之DataFrame二维表基础操作及演示
- 周纪三 周慎靓王元年(辛丑,公元前320年)——摘要
- 如何让div靠右_div对齐 CSS实现DIV居中对齐 div居右对齐 div居左对齐
- 干货 | Apache Flink 入门技术分享 PPT(多图预警)
- Arduino和SX1278的那些事
- 单目相机三维姿态解算
- java软件工程师自我评价_java软件工程师自我评价简历范文
- 诗歌中的宇宙飞船和电子计算机代表什么,《宇宙飞船的避火衣》阅读理解及答案...
- 大数据在保险界的应用
- 如何按要求比较两个数的大小(不使用大于、小于以及if语句)