Django通道 - 在连接上发送数据

问题描述 投票:0回答:1

我正在使用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

正确的方法是什么?

django websocket django-channels
1个回答
0
投票

首先,您需要在向客户端发送数据之前接受连接。我假设你使用的是 AsyncWebsocketConsumer(你应该)作为更低级别的 AsyncConsumer 无法 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)
© www.soinside.com 2019 - 2024. All rights reserved.