Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the best approach to use Web Sockets with Django projects?

I am starting to work on a new Django project that requires sockets. I've searched internet and found this and this tutorials. There is also a lot of outdated stuff out there.

Can anyone recommend the best approach to use sockets with Django? I am using Django 1.7. Thanks.

like image 536
chabislav Avatar asked Jul 06 '15 21:07

chabislav


4 Answers

See Django Channels project.

Channels is a project to make Django able to handle more than just plain HTTP requests, including WebSockets and HTTP2, as well as the ability to run code after a response has been sent for things like thumbnailing or background calculation.

like image 162
Stan Zeez Avatar answered Nov 12 '22 16:11

Stan Zeez


Websockets are basically unsupported by django because django is based on WSGI which doesn't support websockets. My best suggestion is to use something like tornado for where you need websockets. You should be able to access all your models in tornado (could use the django templating system too if you wanted) you'll just be missing the django url system because tornado has its own.

The suggestions you give would work too, but they're based on Socket.IO which is is javascript. If you're happy with javascript on the server side (you don't really have much of a choice on the client), then either one would be fine. If you want python, take a look at tornado.

like image 25
CrazyCasta Avatar answered Nov 12 '22 17:11

CrazyCasta


Well, this is not a short topic.

Django is blocking framework, so it is not working in async style. You need something like http://autobahn.ws, it have websocket implementation (running on twisted or asyncio, it depends what version of python you're using).

Authobahn will be running as an external service, your clients will connect to it. If you need to connect it with django, django can post events to websocket worker (e.g. via HTTP or other protocol you like), and then websocket worker will publish your event to clients.

like image 2
coldmind Avatar answered Nov 12 '22 15:11

coldmind


I've used successfully gevent-websocket and django with socketio. You have to use the special runserver_socketio-command, to allow websocket connections.

like image 2
Daniel Avatar answered Nov 12 '22 15:11

Daniel