首页 > 解决方案 > 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

正确的方法是什么?

标签: djangowebsocketdjango-channels

解决方案


首先,您需要在向客户端发送数据之前接受连接。我假设你正在使用AsyncWebsocketConsumer(你应该)因为更底层的AsyncConsumerhas 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)

推荐阅读