Using Flask for Scientific Web Applications

Implementing error checking in the template

What happens if the user gives wrong input, for instance the letters asd instead of a number? Actually nothing! The FloatField object checks that the input is compatible with a real number in the form.validate() call, but returns just False if this is not the case. Looking at the code in controller.py,

def index():
    form = InputForm(request.form)
    if request.method == 'POST' and form.validate():
        result = compute(form.A.data, form.b.data,
                         form.w.data, form.T.data)
    else:
        result = None

we realize that wrong input implies result = None and no computations and no plot! Fortunately, each field object gets an attribute error with information on errors that occur on input. We can write out this information on the web page, as exemplified in the template view_errcheck.html:

<form method=post action="">
<table>
  {% for field in form %}
    <tr>
    <td>{{ field.name }}</td><td>{{ field(size=12) }}</td>
    <td>{{ field.label }}</td>
    {% if field.errors %}
      <td><ul class=errors>
      {% for error in field.errors %}
        <li><font color="red">{{ error }}</font></li>
      {% endfor %}</ul></td>
    {% endif %}
    </tr>
  {% endfor %}
</table>
<p><input type=submit value=Compute></form></p>
<p>
{% if result != None %}
<img src="{{ result }}" width="500">
{% endif %}
</p>

Two things are worth noticing here:

  1. We can control the width of the text field where the user writes the numbers, here set to 12 characters.
  2. We can make an extra column in the HTML table with a list of possible errors for each field object.
Let us test the error handling of the A field by writing asd instead of a number. This input triggers an error, whose message is written in red to the right of the label, see Figure 6.


Figure 6: Error message because of wrong input.

It is possible to use the additional HTML5 fields for input in a Flask context. Instead of explaining how here, we recommend to use the Parampool package to automatically generate Flask files with HTML5 fields.