How to receive data from client-side of websocket in Django using Channels

I’m trying to receive a websocket message on the server side. It is not being received. Am I misusing the function? How should this function be implemented as to receive messages and have the 30s live updates running in parallel.

I have created a web server using Django Channels (Daphne) in Python.

It is sending data async to the client via a websocket to live-update charts created using chart.js every 30 seconds. This all works fine.

However, when the user makes a selection and a graph changes, I need new data to be sent immediately. So I'm trying to make a request: the client sends a request to the server via the websocket, the server then receives said request and sends data back to the client.

My problem is, that the websocket is not receiving any data from the client, although everything seems to be alright. Am I misunderstanding how the functions are to be used? Any help will be appreciated!

There are no errors in the log or console, neither server- nor client-side.

See the code for my AsyncWebsocketConsumer:

from asyncio import sleep
from channels.generic.websocket import AsyncWebsocketConsumer
from func.web_read import DatasetBuilder
from datetime import datetime, timedelta, timezone


class ChartDraw(AsyncWebsocketConsumer):

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self._dataset: str
        self._hash_dataset: hash
        self._allmeasurements: DatasetBuilder

    async def connect(self):
        await self.accept()

        self._allmeasurements = DatasetBuilder(1) # some magic, building a dataset

        self._date_end: datetime = datetime.now(timezone(timedelta(hours=+1)))
        self._date_start: datetime = self._date_end - timedelta(minutes=15)
        self._dataset = self._allmeasurements.get_relevant_messages(self._date_start, self._date_end) # gets all the data from a db in the given timeframe.
        self._hash_dataset = hash(str(self._dataset))
        await self.send(str(self._dataset))

        await self.updateDataIfChanged()

    async def updateDataIfChanged(self):
        while True:
            self.updateDate()
            self._dataset = self._allmeasurements.get_relevant_messages(self._date_start, self._date_end)
            if self._hash_dataset != hash(str(self._dataset)):
            await self.send(str(self._dataset))
            self._hash_dataset = hash(str(self._dataset))
            await sleep(30)
            print("30s passed.")

    async def receive(self, text_data):
        print("New Message!")
        print(text_data)

And in the javascript these are the relevant parts:

const socket = new WebSocket('ws://localhost:8000/ws/draw_chart/');

console.log("sending to websocket ...");
try {
     socket.send("DO YOU HEAR ME!?");
} catch (error) {
     console.error("Received error sending data to websocket:", error)
}

It seems there is very little useful documentation on this. I tried to use async.gather to execute receive and my function "updateDataIfChanged" in parallel but to no avail.

As I then realized receive runs in parallel anyways and listens for messages I reverted it back. Shouldn't it output the received text as soon as it is received?

Back to Top