【问题标题】:Auto Refresh div with DataFrame every N seconds每 N 秒使用 DataFrame 自动刷新 div
【发布时间】:2023-04-09 12:54:01
【问题描述】:

我在网上看到了很多解决方案,但找不到最简单的解决方案....简单的烧瓶页面将 df 加载到 html 表中。我想要做的只是每 N 秒重新加载 html 表中的 df,而不是整个页面。

app.py

from flask import Flask, render_template
from app import app
import pandas as pd
import sqlalchemy as sa
cn = sa.create_engine('<my connection string>')

@app.route("/")
def home():
    sql = "select * from <myTable>"
    df = pd.read_sql(sql,cn)
    return render_template("index.html", df=df)

if __name__ == "__main__":
    app.run()

index.html

{%extends "base.html"%}

{% block content %}
<div>
    <table cellpadding="3" cellspacing="3" border=1>
        <thead>
            <tr style="background-color:#a8a8a8">
                <th>Column 1</th>
                <th>Column 2</th>
                <th>Column 3</th>
            </tr>
        </thead>
        <tbody>
            {% for index, row in df.iterrows(): %}
            <tr>
                <td>{{ row["Column_1"] }}</td>
                <td>{{ row["Column_2"] }}</td>
                <td>{{ row["Column_3"] }}</td>
            <tr>
            {% endfor %}
        </tbody>
    </table>
</div>
{% endblock %}

如果对我的后续步骤有任何帮助,我们将不胜感激。

【问题讨论】:

  • 不幸的是,flask 不支持实时重载(至少在核心中)。您应该使用 javascript 每 n 秒获取一次新数据或完全重新加载所有页面。
  • 您可能最终希望使用 Vue 或 React 等前端框架。
  • “我在网上看到了很多解决方案,但找不到最简单的解决方案”。你看到了什么?你试过什么?最简单的解决方案到底是什么意思?正如@Buğraİşgüzar 提到的,通常这是通过 ajax 和 javascript 完成的
  • 我见过一个看起来像这样的 javascript,但我不知道如何在 Flask 应用程序中实现它: setInterval(function(){ $('#test').load('test. html'); },5000);
  • 如果重新加载所有页面对您来说不是问题,您可以使用元标记每隔 N 秒重新加载页面。在您的情况下,这看起来是最简单的方法。详情:w3schools.com/tags/att_meta_http_equiv.asp

标签: python jquery flask


【解决方案1】:

希望对你有帮助 但是,我强烈建议在使用数据框之前对其进行测试并使用测试字符串部分更新您的页面。 ajax 方法和烧瓶路线是正确的。但我不是 100% 确定数据帧到 json 的转换,你必须调查一下

此输出将每 2000 毫秒将“random_dictionary”打印到浏览器控制台

index.html

{%extends "base.html"%}
{% block content %}
<div>
    <table cellpadding="3" cellspacing="3" border=1>
        <!-- Your existing code -->
    </table>
</div>
<script>

//The setInterval() method repeats a given function at every given time-interval.
//Syntax: setInterval(function, milliseconds)

//Calls the update_data_frame function every 2000 milliseconds
var myVar = setInterval(update_data_frame, 2000);

//This function makes a POST request to the flask route "/update"
//The value of return response.json() is the return value of the "/update"
//In your case this is going to be the dataframe
//".then(function(myjson))..." captures the return value to be used as required
function update_data_frame () {
    url = '/update';
    fetch(url,{method:'POST'})
    .then(function(response) {
      return response.json();
    })
    .then(function(myJson)
    {
      store = myJson;
      //This line prints out "{somedata":"somedatavalue","somedata1":"somedatavalue1"}" every 2000 milliseconds
      console.log(store);
    });
  }

</script>
{% endblock %}

----------------------------------------------- ---------------

app.py

@app.route('/update',methods=['POST'])
def update_data_frame():
    #this should be your dataframe
    random_dictionary = {"somedata":"somedatavalue","somedata1":"somedatavalue1"}
    return jsonify(random_dictionary )

【讨论】:

    【解决方案2】:

    我想通了。

    app.py

    @app.route("/")
    def home():
        return render_template("index.html")
    
    @app.route("/df")
    def df4reload():
        sql = "select * from <myTable>"
        df = pd.read_sql(sql,cn)
        return render_template("df.html", df=df)
    

    index.html

    {%extends "base.html"%}
    
    {% block content %}
        <div id="df"></div>
        <script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript"></script>
        <script language="javascript" type="text/javascript">
            $('#df').load('/df'); //Preloads df
            var timeout = setInterval(reloadDF, 5000);    
            function reloadDF () {
                $('#df').load('/df');
            }
        </script>
    {% endblock %}
    

    df.html

    <table cellpadding="3" cellspacing="3" border=1>
        <thead>
            <tr style="background-color:#a8a8a8">
                <th>Column 1</th>
                <th>Column 2</th>
                <th>Column 3</th>
            </tr>
        </thead>
        <tbody>
            {% for index, row in df.iterrows(): %}
            <tr>
                <td>{{ row["Column_1"] }}</td>
                <td>{{ row["Column_2"] }}</td>
                <td>{{ row["Column_3"] }}</td>
            <tr>
            {% endfor %}
        </tbody>
    </table>
    

    它对我有用。如果有人有更好或不同的解决方案,请告诉我。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-03-26
      • 2022-07-06
      • 2017-11-08
      • 2013-09-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多