简体   繁体   English

Python Flask日期实时更新

[英]Python Flask date update real-time

I am building a web app with Python Flask with JavaScript. 我正在使用带有JavaScript的Python Flask构建Web应用程序。 I am a beginner of Javascript. 我是Java语言的初学者。

The process I do now: 我现在执行的过程:

In Flask Python code, 在Flask Python代码中,
1. I get data by scrapping the web (numeric data that updates every minute). 1.我通过抓取网络来获取数据(每分钟更新一次的数值数据)。 2. use the data and calculate something and get the final numbers. 2.使用数据并计算得出最终数字。 3. make a list that contains the final numbers 4. feed the list to a page by adding the list to the page's definition of Flask 5. Now in HTML get the list by capturing it with {{ data|safe }} tag 3.创建一个包含最终数字的列表4.通过将该列表添加到页面的Flask定义中,将该列表提供给页面5.现在,在HTML中,使用{{data | safe}}标签捕获该列表

6. use it with Javascript to make a chart. 6.与Javascript一起使用以制作图表。

The problem is: In the step 1, the data I get is being updated every minute. 问题是:在步骤1中,我获取的数据每分钟都会更新。 For example, on that web page now there are 15 data points. 例如,该网页上现在有15个数据点。 I parse the last 10 data points from that web page and then I put them in a list in my Python and then do the following steps and make a chart on my webpage. 我解析了该网页的最后10个数据点,然后将它们放在Python的列表中,然后执行以下步骤并在网页上绘制图表。 One minute later, in the data source web page, there will be 16 data point available, and I need to get the last 10 data points. 一分钟后,在数据源网页中,将有16个数据点可用,我需要获取最后10个数据点。 In that case, I need to run the python code again to get the latest 10 data points to use them to make a chart on my web page. 在这种情况下,我需要再次运行python代码以获取最新的10个数据点,以使用它们在我的网页上绘制图表。

So, I need to always run the whole python code which is the whole Flask app init.py file and re-render my webpage to see the updated chart. 因此,我需要始终运行整个python代码(即整个Flask应用程序的init.py文件),然后重新渲染我的网页以查看更新后的图表。 If I do not re-run the init.py file in my server, then even after 10 minutes or 2 hours, I will only see the data that I parsed for the first time forever. 如果我没有在服务器上重新运行init.py文件,那么即使经过10分钟或2个小时,我也只会看到我永远第一次解析的数据。

How should I run the Flask and always get the updated data without always re-run the flask init.py every time. 如何运行Flask并始终获取更新的数据,而又不必每次都重新运行flaskinit.py。

I thought about using time.sleep(60) so that the flask app python file is run every 1 minutes. 我考虑过使用time.sleep(60),以便每1分钟运行flask应用程序python文件。 But this is really taking alot of time when my code gets much more thinks to calculate. 但是,当我的代码需要更多的时间来计算时,这确实需要很多时间。 And do not really work. 而且不是真的工作。

How should I solve this problem?? 我应该如何解决这个问题?

Should I use time.sleep ? 我应该使用time.sleep吗? or is threre better way? 还是还有更好的方法?

This is a classic "push" update problem. 这是经典的“推送”更新问题。 Your web server is updated with information that you would like to frequently update (or "push") to your web client front-end. 您的Web服务器已更新,其中包含您要经常更新(或“推送”)到Web客户端前端的信息。

As PJ Santoro suggests , you can repeatedly poll your server (every 10 seconds say) along the lines of "Is there new data? No. Okay. Is there new data? No. Okay. Is there new data? Yes, here it is! Great! Is there new data? ...." It is rather inefficient, but for low data volumes you might never see that problem. 正如PJ Santoro所建议的那样 ,您可以按照“是否有新数据?不。可以。是否有新数据?不。可以。是否有新数据?”重复轮询服务器(每10秒说一次)。 !太棒了!是否有新数据?

A more efficient update system would have the server send an update signal only when new data is ready. 一个更有效的更新系统将使服务器仅在新数据准备就绪时发送更新信号。 There are two major ways to do that: 有两种主要方法可以做到这一点:

  1. Long polling , also known as reverse AJAX and Comet . 长轮询 ,也称为反向AJAXComet Your web page opens an AJAX request on a server URL such as /update_data with a really long timeout (say 30 minutes or an hour). 您的网页在服务器URL(例如/update_data上打开AJAX请求,超时时间非常长(例如30分钟或一个小时)。 When the server has data, it sends it through the waiting AJAX connection. 服务器拥有数据后,它将通过等待的AJAX连接发送数据。 There are complications with this, including managing concurrency on the server side (not historically Python's strong suit) and the fact that even the maximum timeout (~1 hour last I used this technique) might expire without data, and some error handling is needed to manage that. 这样做有一些复杂性,包括管理服务器端的并发性(从历史上看不是Python的强项),以及即使最大超时(我使用此技术的时间大约是1个小时)也可能在没有数据的情况下过期,并且需要一些错误处理才能实现处理。 If you wan to try long polling / reverse AJAX, here is an example using Flask . 如果您想尝试长时间轮询/反向AJAX,下面是使用Flask的示例

  2. WebSockets . WebSockets WebSockets are a much more recent approach to interactive and "push" updates between servers and clients. WebSocket是一种更新得多的方法,用于在服务器和客户端之间进行交互式和“推送”更新。 They're very well-used; 它们被很好地使用。 projects like the Jupyter Notebook depend on them extensively. Jupyter Notebook之类的项目在很大程度上依赖于它们。 They're extremely efficient and well-fit for this kind of incremental update of client state, and the code is often much less Byzantine and confusing than retrofits like reverse AJAX. 它们非常有效并且非常适合这种客户端状态的增量更新,并且与反向AJAX这样的改造相比,它们的拜占庭式代码和混乱的代码通常要少得多。 But...there are complexities with WebSockets too. 但是... WebSockets也很复杂。 Managing concurrency in the Flask server side is still a significant issue, for example. 例如,在Flask服务器端管理并发仍然是一个重要问题。 If you'd like to consider WebSockets as your update mechanism, here is an example of how to use them with Flask. 如果您想将WebSockets视为更新机制,下面是一个如何在Flask中使用它们的示例

Either approach you use, if your data communicated over time grows, you will also need to structure the data transmitted on each update so that it's an incremental update. 无论使用哪种方法,如果随着时间的推移所传递的数据不断增长,则还需要对每次更新中传输的数据进行结构化,以使其成为增量更新。 No mater how good the plumbing, if you transmit thousands of data points every update, it's not going to be fast. 不管如何,管道的性能有多好,如果每次更新都传输数千个数据点,那将不会很快。 But, long polling and WebSockets plumbing should at least get you a great distance toward a legitimate real-time update capability. 但是,长时间的轮询和WebSocket管道检测至少应使您距离合法的实时更新功能更大的距离。

Well... in an ideal world you would separate this into 2 applications: 好吧……在理想的世界中,您可以将其分为两个应用程序:

  • Scrape & Parse Data From the Web (doesn't need to be exposed to the web) 从网上抓取并解析数据(无需暴露于网上)

  • Deliver data to a user via a web app 通过网络应用程序将数据传递给用户

You could use some sort of CI tool (eg Jenkins) to monitor and add the external data into a database and then your Flask app to serve this pre-processed data to your users. 您可以使用某种CI工具(例如Jenkins)来监视外部数据并将其添加到数据库中,然后使用Flask应用程序将这些预处理后的数据提供给用户。

If Steps 1-6 are relatively quick what you could do is setup an XHR endpoint within Flask and then use a setInterval() javascript function to call it on a interval to tell your application to update the data. 如果步骤1-6相对较快,则可以在Flask中设置XHR端点,然后使用setInterval() javascript函数按一定间隔调用它,以告诉您的应用程序更新数据。 Eg: 例如:

setInterval(function() {
    var req = new XMLHttpRequest();
    req.open('GET', '/refresh_data?time=234', true);
    req.onreadystatechange = function(e) {
        if(req.readyState !== 4) {
            return;
        }
        if ([200, 304].indexOf(req.status) === -1) {
            console.warn('Error! XHR failed.');
        }
        else {
            data = JSON.parse(e.target.responseText);
            processData();
            updateChart();
        }
    };
    req.send();
}, 10000);  // time in milliseconds (e.g. every 10 seconds)

And have a flask endpoint like: 并具有如下的烧瓶端点:

@app.route('/refresh_data')
def refresh_data():
    time = requests.args.get('time', type=int)
    if not time:
        return jsonify({status: 'error: incorrect parameters'})
    data = requests.get('http://api.getmoredata.com?time=%s' % time)
    # process the results...
    return jsonify({status: 'success', data: data})

Ideally you'd have some sort of a chart that has a refresh() method where you can pass it new data and just keep adding to it... (eg I'm a fan of D3 for stuff like this). 理想情况下,您将拥有某种带有refresh()方法的图表,您可以在其中传递新数据并不断添加它……(例如,我是D3的爱好者)。

I'd probably remove this from you're init.py code, but it might be acceptable for the "first load". 可能会从您的init.py代码中删除此代码,但对于“首次加载”来说可能是可以接受的。 a flask app (eg any web app) responds to HTTP requests and nothing persists on the server between requests so a time.sleep() would not do much for you... if you want to run persistent code on your server you'd need to look into something like celery to manage background tasks. Flask应用程序(例如任何Web应用程序)响应HTTP请求,请求之间在服务器上没有任何持久性,因此time.sleep()对您没有多大的作用...如果您想在服务器上运行持久性代码,需要研究诸如芹菜之类的东西来管理后台任务。

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

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