Django频道-在Connect上发送数据

时间:2020-06-11 13:28:19

标签: django websocket django-channels

我正在使用网络套接字来向图表提供实时数据。打开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

正确的方法是什么?

1 个答案:

答案 0 :(得分:1)

首先,您需要先接受连接,然后再将数据发送到客户端。我认为您正在使用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)