Flask for Loops - Printing Dict Data

Julian, Thu 06 April 2017, Flask

decorators, Flask, learning, loops, python, tutorial

Thanks to the 100 Days of Code Challenge, this week I took the plunge and dove into Python Flask.

It’s not the easiest beast to tame but once you wrap your head around it, it’s not so bad!

One of the concepts I struggled with early on was how to return more than “just” a single string to the Flask app web page.

Python Setup

Check out the full code for this here.

@app.route("/birthdays")
def birthdays():
    dates = {"Julian": 25, "Bob": 26, "Dan": 47, "Cornelius": 3}
    return render_template("birthdays.html", dates=dates)

HTML Setup

With the main.py file all set up, we can focus on birthdays.html. (Again, all of this is in the code Repo!).

.thick-border {
        border: 3px solid black;
        border-collapse: collapse;
}
<table class="centered thick-border">
        <tr>
                <th>First name</th>
                <th>Age</th>
        </tr>
</table>

Flask in Action

{% for k, v in dates.items() %}
<tr>
    <td>{{ k }}</td>
    <td>{{ v }}</td>
</tr>
{% endfor %}

Final Result

<table class="centered thick-border">
        <tr>
                <th>First name</th>
                <th>Age</th>
        </tr>
        {% for k, v in dates.items() %}
                <tr>
                        <td>{{ k }}</td>
                        <td>{{ v }}</td>
                </tr>
        {% endfor %}
</table>

Table populated by Python dict code

Learning Points

Next Steps

You’ll be seeing more Flask in the coming weeks (I hope!). I’d actually like to wrap this for loop around the data set for this week’s code challenge… hmm…

Keep Calm and Code in Python!

— Julian