首页 > 解决方案 > 如何使用 Flask 从 Postgresql 数据库中获取数据并显示 HTML 表

问题描述

  import psycopg2
    from flask import Flask, render_template
    app = Flask(__name__)
    con = psycopg2.connect(database="Angels_Attic", user="postgres", password="", host="127.0.0.1", port="5432")
    cursor = con.cursor()

    @app.route("/", methods=['post', 'get'])
    def test():  
        cursor.execute("select * from cart")
        result = cursor.fetchall()
        return render_template("test.html", data=result)

测试.html

<html>
<body>
    <div>
        {% for row in data %}
        <p>{{ row[0] }}</p>
        <p>{{ row[1] }}</p>
        {% endfor %}
    </div>

    </body>
    </html>

我得到的错误:IndentationError: unindent does not match any external indentation level

当我运行这个烧瓶文件时,我遇到了一堆错误。我只想知道如何正确连接数据库并使用复杂的 SQL 查询从中获取数据并将其显示在 HTML 文件中。请让我知道如何进行。

标签: pythonpostgresqlflask

解决方案


这与代码的逻辑无关,只是代码的缩进应该是这样的:从import下面的所有行中删除空格

import psycopg2
from flask import Flask, render_template
app = Flask(__name__)
con = psycopg2.connect(database="Angels_Attic", user="postgres", password="", host="127.0.0.1", port="5432")
cursor = con.cursor()

@app.route("/", methods=['post', 'get'])
def test():  
    cursor.execute("select * from cart")
    result = cursor.fetchall()
    return render_template("test.html", data=result)

推荐阅读