简体   繁体   English

在Django项目中使用Web套接字的最佳方法是什么?

[英]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. 我开始研究一个需要套接字的新Django项目。 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? 任何人都可以推荐使用Django套接字的最佳方法吗? I am using Django 1.7. 我正在使用Django 1.7。 Thanks. 谢谢。

Websockets are basically unsupported by django because django is based on WSGI which doesn't support websockets. django基本上不支持Websockets,因为django基于不支持websockets的WSGI。 My best suggestion is to use something like tornado for where you need websockets. 我最好的建议是使用像龙卷风这样的东西,你需要的是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. 您应该能够访问龙卷风中的所有模型(如果您愿意,也可以使用django模板系统)您只是会错过django url系统,因为龙卷风有它自己的。

The suggestions you give would work too, but they're based on Socket.IO which is is javascript. 你给出的建议也会起作用,但它们都是基于Socket.IO,这是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. 如果你对服务器端的javascript感到满意(你在客户端上没有太多的选择),那么任何一个都可以。 If you want python, take a look at tornado. 如果你想要python,请看看龙卷风。

Well, this is not a short topic. 嗯,这不是一个简短的话题。

Django is blocking framework, so it is not working in async style. Django是阻塞框架,因此它不能以异步方式工作。 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). 你需要像http://autobahn.ws这样的东西,它有websocket实现(在twisted或asyncio上运行,它取决于你正在使用的python版本)。

Authobahn will be running as an external service, your clients will connect to it. Authobahn将作为外部服务运行,您的客户将连接到它。 If you need to connect it with django, django can post events to websocket worker (eg via HTTP or other protocol you like), and then websocket worker will publish your event to clients. 如果你需要将它与django连接,django可以将事件发布到websocket worker(例如通过HTTP或你喜欢的其他协议),然后websocket worker将你的事件发布给客户端。

I've used successfully gevent-websocket and django with socketio . 我已成功使用gevent-websocket和django与socketio You have to use the special runserver_socketio -command, to allow websocket connections. 您必须使用特殊的runserver_socketio命令来允许websocket连接。

See Django Channels project. 请参阅Django Channels项目。

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. Channels是一个项目,使Django能够处理的不仅仅是普通的HTTP请求,包括WebSockets和HTTP2,以及在为缩略图或背景计算等事件发送响应后运行代码的能力。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM