每N秒使用DataFrame自动刷新div [英] Auto Refresh div with DataFrame every N seconds

查看:92
本文介绍了每N秒使用DataFrame自动刷新div的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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.

推荐答案

我知道了.

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

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.

这篇关于每N秒使用DataFrame自动刷新div的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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