Python displaying SQLite3 database records on a Fl

2019-04-17 13:15发布

问题:

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)

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 %}

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 }}

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.

回答1:

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 %}