Flask数据库更改而不进行轮询时更新所有客户端的最佳方法是什么? [英] What is the best way to update all clients when Flask database changes without polling?

查看:169
本文介绍了Flask数据库更改而不进行轮询时更新所有客户端的最佳方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

目前我有一个Flask服务器,它运行一个小的Web前端以及一个命令行接口到同一台服务器。基本的想法如下所示:

 < Top section:允许文件上传> 
*数据库文件列表

<第二部分:允许文件操作/上传>
*数据库中的文件列表

<第三部分:不是文件,但仍允许数据库更改>
*从数据库中创建的事物列表

现在,目前如果CLI或其他客户端对数据库进行更改,则不会更新其他客户端。我有一些工作与JS轮询和重写每10秒的文件列表,但这似乎既低效,也将看起来非常混乱,如果我不得不这样做的每一节。我看到在各种论坛中提到的websockets,但我从来没有使用它们,我不确定是否会添加一个痛苦。我不想重写所有的功能。



最终结果:如何更新所有客户端比轮询/如何有效地进行轮询?

解决方案

是的,你是正确的。您需要 套接字 。网上有很多文章,但我想给出一个总结,并试图解释为什么套接字将是最适合您的要求。



套接字的方式实现客户端和服务器之间的双向通信而不需要轮询。

有一个名为客户端和服务器之间的双向通信。

然后,对于您想要发送的场景当一个客户端对数据库或类似的东西做一些工作时,所有连接的客户端都会发生变化,您将需要使用广播。在启用广播选项的情况下发送消息时,连接到命名空间的所有客户端都会收到它,包括发件人。 这里可以找到使用Flask-SocketIO进行广播的详细信息。


Currently I have a Flask server that runs a small web frontend as well as a command line interface to that same server. The basic idea looks like this:

<Top section: allows file upload>
   * list of files from database

<Second section: allows file manipulation/ upload>
  * list of files  from database

<Third section: Not files, but still allows for database changes>
  * list of things made from database  

Now this works well from the front end, but currently if the CLI or another client makes a change to the database, it doesn't update other clients. I have it somewhat working with JS polling and rewriting the list of files every 10s, but that seems both inefficient and also would look very messy if I had to do it for every section. I saw websockets mentioned in various forums, but I've never used them and am unsure if it would be a pain to add. I'm not trying to rewrite the whole thing for a single feature.

Final takeaway: How to update all clients better than polling/ how to do polling efficiently?

解决方案

Yes you are correct. You need sockets. There are bunch of articles over the internet but I would like to give a summary and try to explain why sockets will be the best fit to your requirements.

Sockets are way of achieving two way communication between client and server without the need of polling.

There is a package called Flask-SocketIO

Flask-SocketIO gives Flask applications access to low latency bi-directional communications between the clients and the server.

Then for the scenario where you would like to send changes to all the connected client when one client does some work to your database or something similar, you will need to use broadcasting. When a message is sent with the broadcast option enabled, all clients connected to the namespace receive it, including the sender. Here you can find details of the broadcasting using Flask-SocketIO.

这篇关于Flask数据库更改而不进行轮询时更新所有客户端的最佳方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆