Python在Flask本地网站上显示SQLite3数据库记录 [英] Python displaying SQLite3 database records on a Flask local website
问题描述
在本地Flask网页的烧瓶帮助下,我一直在尝试显示在python中创建的SQLite3数据库中的记录。我使用python中的代码将一条记录的每个collumn分配给一个字典变量:
I have been trying to display records from a SQLite3 database created in python with the help of flask on a local Flask webpage. I assigned each collumn of the a record to a dictionary variable using this code in 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文件包含以下代码:
This code is used with a HTML page where I wanted the records to be shown. The HTML file contained this code:
<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,标题,图片,评级,但没有相应的数据库值。我试过测试它,发现如果我输入:
This does not seem to do what I want as it prints out ID, Title, Picture, Rating but without the corresponding database value. I have tried testing it and found that if I enter:
{{ Recipes }}
在HTML代码中,它显示数据库中的所有记录。这表明字典中填满了数据,但是在它之间的某处,试图显示该字典,因此无法被调用。
In the HTML code then it displays all of the records from the database. This shows that the dictionary is filled with data but somewhere between itself and trying to display it, it fails to be called upon.
推荐答案
您正在尝试使用 Recipes
列表中的 ID
等属性,不包含每个单独的字典。使用配方
名称,它被绑定到当前条目的迭代:
You are trying to use the ID
, etc. attribute on the Recipes
list, not on each individual dictionary contained. Use the recipe
name, it is bound to the current entry for the iteration:
{% 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 %}
这篇关于Python在Flask本地网站上显示SQLite3数据库记录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!