Consumers
因为建立Channels最底层的解释接口是ASGI,被用来连接复杂应用的操作接口
当然你也可以忽略consumers而使用其他Channels部分,像routing,session等等
基础布局
consumers 的子类有
channels.consumer.AsyncConsumer
channels.consumer.SyncConsumer
SyncConsumer的一个基础例子
from channels.consumer import SyncConsumer
class 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 AsyncConsumer
class 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"],
})
什么时