Auto Refresh div with DataFrame every N seconds

China☆狼群 提交于 2020-12-15 05:19:30

问题


I have seen a lot of solutions for this around the net but can't find the easiest solution for this .... simple flask page that loads a df into the html table. All I want to do is reload just the df in the html table every N seconds and not the whole page.

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 %}

Any help on my next steps would be greatly appreciated.


回答1:


I hope this helps you, However I highly recommend testing this out and updating your page partially with a test string before working with the data frame. The ajax method and the flask routes are correct. But I am not 100% sure about the conversion of dataframes to json, you will have to look into that

The output of this will print out the "random_dictionary" to your browser console every 2000 milliseconds

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:


I figured it out.

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>

It works for me. If anyone has any better or different solutions, please let me know.



来源:https://stackoverflow.com/questions/62027285/auto-refresh-div-with-dataframe-every-n-seconds

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!