【问题标题】:Python displaying SQLite3 database records on a Flask local websitePython 在 Flask 本地网站上显示 SQLite3 数据库记录
【发布时间】:2015-03-31 06:36:33
【问题描述】:

我一直在尝试在本地 Flask 网页上显示使用 python 创建的 SQLite3 数据库中的记录。我在 python 中使用以下代码将记录的每个列分配给字典变量:

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 代码中显示数据库中的所有记录。这表明字典充满了数据,但在它自身和试图显示它之间的某个地方,它无法被调用。

【问题讨论】:

    标签: html python-3.x dictionary sqlite flask


    【解决方案1】:

    您尝试在 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 %}
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-07-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-04-14
      相关资源
      最近更新 更多