Filipe Aleixo
Filipe Aleixo

Reputation: 4244

Django channels - sending data on connect

I'm using a websocket to feed a chart with live data. As soon as the websocket is opened, I want to send the client historical data, so that the chart doesn't start loading only with the current values.

I want to do something like this, if it was possible:

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

What's the right way to do it?

Upvotes: 1

Views: 1488

Answers (1)

Ken4scholars
Ken4scholars

Reputation: 6296

First you need to accept the connection before sending data to the client. I assume you're using AsyncWebsocketConsumer(and you should) as the more low-level AsyncConsumer has not method 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)

Upvotes: 3

Related Questions