You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过Flask后端从PostgreSQL动态加载数据到HTML表格

解决Flask+PostgreSQL动态加载表格数据的问题

核心问题分析

你的代码存在两个关键问题导致数据无法显示:

  • 数据库查询逻辑写在路由函数外部,只会在应用启动时执行一次,且未将查询结果传递给模板
  • 模板未使用Jinja2循环语法渲染动态数据

1. 修改app.py代码

将数据库查询逻辑移到路由函数内部,并把查询结果传递给模板:

from flask import Flask, render_template
import psycopg2

app = Flask(__name__)

@app.route("/schemes")
def schemes():
    conn = None
    cur = None
    data = []
    try:
        # 建立数据库连接
        conn = psycopg2.connect(
            database="schemes", 
            user="sukku",
            password="schemes", 
            host="localhost", 
            port="5432"
        )
        cur = conn.cursor()
        # 建议明确指定字段顺序,避免表结构变化导致渲染错位
        cur.execute('''SELECT year, project_count, project_cost, tifs_share FROM schemes_data''')
        data = cur.fetchall()
    finally:
        # 确保关闭游标和连接,避免资源泄漏
        if cur:
            cur.close()
        if conn:
            conn.close()
    # 将查询数据传递给模板
    return render_template("schemes.html", schemes_data=data)

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

注意:需确保schemes_data表的字段名和SQL中指定的year、project_count、project_cost、tifs_share完全匹配,若表字段名不同,替换为实际字段名即可。

2. 修改schemes.html模板

用Jinja2循环语法替换静态表格行,渲染动态数据:

<table class="fl-table">
    <thead>
    <tr>
        <th>Year</th>
        <th>No.of projects sanctioned</th>
        <th>Cost of Project.( Rs in lakhs)</th>
        <th>TIFS Share sanctioned.( Rs in lakhs)</th>
    </tr>
    </thead>
    <tbody>
    <!-- 遍历传递过来的schemes_data数据 -->
    {% for row in schemes_data %}
    <tr>
        <td>{{ row[0] }}</td>
        <td>{{ row[1] }}</td>
        <td>{{ row[2] }}</td>
        <td>{{ row[3] }}</td>
    </tr>
    {% endfor %}
    </tbody>
</table>

若想通过字段名直接访问(如{{ row.year }}),可改用字典游标:
在app.py中导入DictCursor,修改游标创建代码:

from psycopg2.extras import DictCursor
cur = conn.cursor(cursor_factory=DictCursor)

模板中即可写:

<td>{{ row.year }}</td>
<td>{{ row.project_count }}</td>

内容的提问来源于stack exchange,提问作者Sukesh Raghav

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.27 17:12:46