Accessing Continuous Data from Websockets in Django Channels

Improved Question:

In the file "apisGo.py", I have two methods that retrieve data from servers through websockets. This data is updated continuously, meaning the function never ends. The issue is that I need to receive the contents of the "msg" variable from both "apiA" and "apiB" in my "WSConsumer" class, so I can send it to the frontend. What is the correct way to do this?

file apisGo.py

async def apiA():
    async with websockets.connect('wss://ws-api...)) as ws:

        msg = {"id": "%s" % (uuid),
               "type": "",
               "topic": "",
               "response": True}
        msg = json.dumps(msg)

        await ws.send(msg)

        while True:
            msg = await ws.recv()


async def apiB():
    async with websockets.connect('wss://ws-api...)) as ws:

        msg = {"id": "%s" % (uuid),
               "type": "",
               "topic": "",
               "response": True}
        msg = json.dumps(msg)

        await ws.send(msg)

        while True:
            msg = await ws.recv()
            

async def main():
    task1 = asyncio.create_task(apiA())
    task2 = asyncio.create_task(apiB())

    await asyncio.gather(task1, task2)


if __name__ == "__main__":
    asyncio.run(main())

file "consumers.py":

import apisGo

class WSConsumer(WebsocketConsumer):
    def connect(self):
        self.accept()
        asyncio.run(apisGo.main())

I considered using global variables in the "apisGo.py" file and using the "import multiprocessing" in "consumers.py" to create two routines: one to initiate the requests "asyncio.run(apisGo.main())" and another to access the global variables. But I am not sure if this is the correct approach, I would like guidance.

Back to Top