Run Django app and also connect to a websocket

I want to run my Django app as normal but at the same time also connect to a websocket and use the data that is coming from there. Is it possible to do both of these at the same time using ASGI?

If you’re looking for a websocket connection, you want to look at Channels.

I’ve looked at Channels and it seems to add a huge amount of architectural complexity for what should maybe just be a small feature? I would prefer to avoid it.

I was under the impression that ASGI would obsolete Channels? Is that false?

There may be some overlap of functionality between ASGI and Channels, but it won’t obsolete it - there are some distinctions between the two. Current Django/ASGI is still built around the “request/response” model, even if the Views are starting to be able to process asynchronously.

That “small feature” as you describe it is a completely different protocol - you’re no longer working with discrete requests but with continual data streams creating event-driven interactions.

Ken

1 Like

I’m not sure whether it’s fully incompatible. Or at least I hope there’s a way.

I think I’ve seen a tutorial run a websocket server in the same process by patching asgi.py. I guess that works by multiplexing on the same host:port combination based on what you get?

The Django docs hint at being able to compose apps using ASGI but it’s a throw away sentence more than anything else. (Anything more on that? Or could somebody help me add it?)

For my use case, I need my app to be able to connect to a websocket in parallel to running the web app. Maybe that’ll be easier by composing one await loop next to the main Django app?

Specifically there’s this tutorial: https://dev.to/jaydenwindle/adding-websockets-to-your-django-app-with-no-extra-dependencies-2f6h

There’s this tutorial that does Websockets from just Django: https://dev.to/jaydenwindle/adding-websockets-to-your-django-app-with-no-extra-dependencies-2f6h

Any luck on this? Did you end up following something similar to the article you posted? I’m trying to accomplish something very similar in my django app.

You should track the other conversation here: Add a websocket client to Django (not a server)