Setup websockets with Python/Django

Viewed 96

Is there some way I could setup my architecture like this for my web application:

Backend - Django + DRF (Rest API)
Frontend - React

And on the backend setup a websocket Client to listen to an external websocket Server and then forward the data from the Client to a new Server that I will create. So in React I could listen to this websocket Server that I have created?

I tried implementing this in React to listen to an external websocket Server, but it just gave me headaches trying to use proxy to avoid CORS problems.

How should I approach this? Am I thinking straight here?

1 Answers

Hello Marcus C and welcome to StackOverflow!

Since you didn't post any code yourself I can't give you any concrete examples, but I can point you in the right direction. As you said yourself trying to use an external WebSockets server (such as Node.js with socket.io) is a pain. For this purpose the Django Channels library exists. It is really useful as it allows direct access to database and other Django-related stuff.

If you run Django in a Docker container, the best way to use Channels is to run two separate containers, one with say gunicorn or uWSGI servers for the synchronous part and another with Channels' recommended Daphne server for asynchronous part, both proxied by nginx. Standard (or rather common) way is to use /ws path prefix for the asynchronous endpoints.

Related