django - Django 频道 - 在连接时发送数据
问题描述
我正在使用 websocket 为图表提供实时数据。打开 websocket 后,我想发送客户端历史数据,以便图表不会仅使用当前值开始加载。
如果可能的话,我想做这样的事情:
from channels.db import database_sync_to_async
class StreamConsumer(AsyncConsumer):
async def websocket_connect(self, event):
# When the connection is first opened, also send the historical data
data = get_historical_data(1)
await self.send({
'type': 'websocket.accept',
'text': data # This doesn't seem possible
})
# This is what I use to send the messages with the live data
async def stream(self, event):
data = event["data"]
await self.send({
'type': 'websocket.send',
'text': data
})
@database_sync_to_async
def get_historical_data(length):
.... fetch data from the DB
正确的方法是什么?
解决方案
首先,您需要在向客户端发送数据之前接受连接。我假设你正在使用AsyncWebsocketConsumer
(你应该)因为更底层的AsyncConsumer
has not 方法websocket_connect
from channels.db import database_sync_to_async
class StreamConsumer(AsyncWebsocketConsumer):
async def websocket_connect(self, event):
# When the connection is first opened, also send the historical data
data = get_historical_data(1)
await self.accept()
await self.send(data)
# This is what I use to send the messages with the live data
async def stream(self, event):
data = event["data"]
await self.send(data)
推荐阅读
- basic-authentication - OpenApi Basic Auth 注解
- mysql - 在 MySQL 中使用子查询时检查插入表的重复条目
- python - 使用 VS Code 运行 Python - 基础知识
- linux - 如何在 ls 输出中按照从左到右的顺序更改文件名?
- python - python-telegram-bot 错误内联:未指定输入消息内容
- mysql - mysql查询以获取用户尚未完成的preq任务
- r - 是否有用于将列表中的向量修剪为最小向量长度的 R 函数?
- create-react-app - npm 启动错误:EPERM:不允许操作,mkdir 'C:\Windows\System32\robinhood\node_modules\.cache'
- c# - C# .net 串口接收缓冲区始终为空
- macos - Turn off Dark Mode only for Safari in macOS Big Sur 11.6