Python 在 Flask 本地网站上显示 SQLite3 数据库记录

Python displaying SQLite3 database records on a Flask local website

我一直在尝试在本地 Flask 网页上借助 Flask 显示在 python 中创建的 SQLite3 数据库中的记录。我使用 python:

中的代码将 a 记录的每个列分配给字典变量
import sqlite3
app.database = "Recipe.db"

@app.route('/recipes')
def recipes():
    g.db = connect.db()
    cur = g.db.execute('SELECT * from Recipe_tbl')
    Recipes = [dict(ID=row[0],
                    Title=row[1],
                    Picture=row[2],
                    Rating=row[3]) for row in cur.fetchall()]
    g.db.close()
    return render_template('recipes.html', Recipes=Recipes)

此代码与我希望显示记录的 HTML 页面一起使用。 HTML 文件包含此代码:

<h1>Recipes</h1>
{% for recipe in Recipes %}
    <strong>ID:</strong> {{ Recipes.ID }} <br>
    <strong>Title:</strong> {{ Recipes.Title }} <br>
    <strong>Picture:</strong> {{ Recipes.Picture }} <br>
    <strong>Rating:</strong> {{ Recipes.Rating }} <br>
{% endfor %}

这似乎没有达到我的要求,因为它打印出 ID、标题、图片、评级,但没有相应的数据库值。我试过测试它,发现如果我输入:

{{ Recipes }}

在 HTML 代码中,它会显示数据库中的所有记录。这表明字典中充满了数据,但在它自身和试图显示它之间的某处,它无法被调用。

您正试图在 Recipes 列表 上使用 ID 等属性,而不是在包含的每个单独词典上。使用 recipe 名称,它绑定到迭代的当前条目:

{% for recipe in Recipes %}
    <strong>ID:</strong> {{ recipe.ID }} <br>
    <strong>Title:</strong> {{ recipe.Title }} <br>
    <strong>Picture:</strong> {{ recipe.Picture }} <br>
    <strong>Rating:</strong> {{ recipe.Rating }} <br>
{% endfor %}