Filipe Aleixo
Filipe Aleixo

Reputation: 4244

Is this a good way to stream data through django channels?

I have a database where new data is being inserted every second. When the websockets connection is first established, I want to send all the data using django channels. Then, I want the new data data that goes every second into the database to be sent through the same websocket. I have the following consumers.py

class DataConsumer(AsyncConsumer):

    async def websocket_connect(self, event):
        print("connected", event)
        await self.send({
            "type": "websocket.accept"
        })

        obj = ... send the whole db

        await self.send({
            'type': 'websocket.send',
            'text': obj
        })

        while True:
            await asyncio.sleep(1)

            obj = ... send only new records

            await self.send({
                'type': 'websocket.send',
                'text': obj
            })

    async def websocket_receive(self, event):
        print("receive", event)

    async def websocket_disconnect(self, event):
        print("disconnected", event)

Here Django Channels - constantly send data to client from server they mention that the loop will never exit if the user disconnects. They present a potential fix, but I don't understand it well. How could I fix it?

Upvotes: 1

Views: 1656

Answers (1)

hardik24
hardik24

Reputation: 1058

Basically what you have to do is rather than writing, while True:. Rather, you should define a global variable say is_connected and on connection set it to True and on disconnected make is False and while condition must use this variable as follow:

class DataConsumer(AsyncConsumer):

    async def websocket_connect(self, event):
        print("connected", event)
        await self.send({
            "type": "websocket.accept"
        })

        obj = ... send the whole db

        await self.send({
            'type': 'websocket.send',
            'text': obj
        })

        # here set is_connected to True 
        self.is_connected = True

        while is_connected:
            await asyncio.sleep(1)

            obj = ... send only new records

            await self.send({
                'type': 'websocket.send',
                'text': obj
            })

    async def websocket_receive(self, event):
        print("receive", event)

    async def websocket_disconnect(self, event):

        # set is_connected to false
        is_connected = False

        print("disconnected", event)

Upvotes: 2

Related Questions