1

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?

1 Answer 1

3

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)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.