转换 pandas 数据帧后将 HTML table 插入页面

Inserting HTML table into page after converting pandas dataframe

我试图在从 pandas 数据框转换后在我的 Flask 应用程序的页面上显示 HTML table。该应用程序首先从 'home' 页面上的下拉菜单中获取三个变量,然后根据这些创建一个数据框(网络根据选择从 URL 中抓取某些数据)。

点击主页上的提交按钮(这也会更改页面)后,我将 df 保存为 pickle 文件,这样它就可以打开并转换为 HTML table另一页...

下面是我的 show_results 方法,该方法在尝试添加 table 之前调用获取结果(这是数据框被 pickle 的地方)然后 returns 模板:

def show_results():
    fetch_results()
    return render_template("get_results.html")
    cache_dir = os.path.join(ROOT_PATH, "cache")
    cache_file = os.path.join(cache_dir, "file.p")
    if request.method == "POST":
        with open(cache_file, "rb") as fid:
            results = pickle.load(fid)
        results_table = results.to_html()
    print(results_table)

我的总体想法是 return 模板,然后在...

之后添加 table

目前,get_results.html 只有一个导航栏和一个 header。我尝试按照 GeeksForGeeks 教程进行操作:

https://www.geeksforgeeks.org/python-pandas-dataframe-to_html-method/

有什么指点吗?

您可以将数据帧作为 table 传递给模板 html,例如:

@app.route('/dropDownVals', methods=['GET' ,'POST'])
def getDropDownVals():
    conn = sqlite3.connect("Casa.db")
    df = pd.read_sql_query("""SELECT * FROM(
    SELECT DISTINCT TEAMA FROM [TABLE]

    UNION 

    SELECT DISTINCT TEAMB FROM [TABLE]
    ) AS X
    WHERE TEAMA NOT LIKE '%#%'
    ORDER BY 1""", conn)
    c = conn.cursor()
    conn.commit()  # commit needed
    c.close()
    return render_template('findCollisions.html', tables=[df.to_html(classes='data', header="true")], titles=df.columns.values)

然后在模板页面上,您可以使用 Jinja 模板获取这些值:

 {% for table in tables %}
 {{titles[loop.index]}}
 {{ table|safe }}
 {% endfor %}