Flask Jinja template list of dictionaries



examples/flask/jinja-list-of-dictionaries/app.py
from flask import Flask, render_template
import csv
app = Flask(__name__)

@app.route("/")
def main():
    planets = read_csv_file('planets.csv')

    return render_template('main.html',
        title     = "Planets",
        planets   = planets,
    )

def read_csv_file(filename):
    planets = []
    with open(filename) as fh:
        rd = csv.DictReader(fh, delimiter=',')
        for row in rd:
            planets.append(row)
    return planets

examples/flask/jinja-list-of-dictionaries/templates/main.html
<h1>{{ title }}</h1>
<table>
  {% for planet in planets %}
     <tr>
       <td>{{ planet['Planet name'] }}</td>
       <td>{{ planet['Distance (AU)'] }}</td>
       <td>{{ planet['Mass'] }}</td>
     </tr>
  {% endfor %}
</table>

examples/flask/jinja-list-of-dictionaries/test_app.py
import app

def test_app():
    web = app.app.test_client()

    rv = web.get('/')
    assert rv.status == '200 OK'
    assert b'<h1>Planets</h1>' in rv.data
    assert b'<td>Mercury</td>' in rv.data