Foundations of Python Network Programming

(WallPaper) #1

Chapter 11 ■ the World Wide Web


196



    {% for p in payments %}
    {% set prep = 'from' if (p.credit == username) else 'to' %}
    {% set acct = p.debit if (p.credit == username) else p.credit %}
  • ${{ p.dollars }} {{ prep }} {{ acct }}
    for: {{ p.memo }}

  • {% endfor %}

Make payment | Log out
{% endblock %}

Note that the code is not interested in displaying the current user’s account name over and over again as it loops
to display their incoming and outgoing payments. So, it instead figures out, for each payment, whether the credit
or debit account name is the one that matches the current user and then makes sure that it prints the other account
name instead—using with the correct preposition so that the user can tell which way their money has flowed. This is
possible thanks to Jinja2’s {% set ... %} command, which makes quick little presentation calculations like this quite
easy to do in-template when the designer realizes what they want.
There often seem to be dozens of ways that the user can fail to fill out a form correctly, and Listing 11-6 prepares
itself by expecting to receive a complaint string for prominent display at the top of the form, if such a string is provided.
Beyond this nicety, the code is mostly repetitive: three form fields that, if the form was filled out incorrectly and is
being redisplayed, need to be prefilled with whatever text the user already had there when they tried submitting it.


Listing 11-6. The pay.html Jinja2 Template


{% extends "base.html" %}
{% block title %}Make a Payment{% endblock %}
{% block body %}



{% if complaint %}{{ complaint }}{% endif %}



| Cancel

{% endblock %}

It is a best practice to have an escape route next to every submit button on a site. Experiments suggest that users
make the fewest mistakes if, however, the escape route is obviously smaller and less significant than the default action
of submitting the form—and it is especially important that the escape route not look like a button!
So, pay.html is careful to make its “Cancel” escape route a simple link, visually separated from the button by the
conventional pipe symbol (|) that is currently popular in this visual context.
If you want to try this application, you can check out the source code, enter the chapter11 directory that contains
bank.py, app_insecure.py, and the associated templates/ directory, and type the following:


$ pip install flask
$ python3 app_insecure.py


The result should be an announcement that it is up and running at a URL that it will print to your screen.

Free download pdf