Full-Stack Development Hackbright Part-Time Classes

Model Fun

Week 5

For the second class in Week 5, continue to work on the "Extending the App" challenges from the previous lab. Ideally, make sure you have worked through at least one challenge that involves changing the model somehow, and another that involves template changes.

Notes

For the validation exercise, one common question was "How do I check that the thing the user entered is a string or a number?". Flask request.form values are always strings, so we can't just do a basic check.

This is a great use of try. We try to do the conversion and if it fails, we have a pretty good guess why:

calories = request.form.get('calories')

try:
    calories = int(calories)
except:
    raise Exception("Calories must be an integer")

We can do the same for float, too:

price = request.form.get('price')

try:
    price = float(price)
except:
    raise Exception("price must be a number")

What about if we don't want the string to be a number?

name = request.form.get('name')

try:
    name = int(name)
    raise Exception("Name should have non-number characters")
except:
    pass

What's going on there?

Well, we first try to convert name to int. We want this to fail, because name shouldn't be a number. If it does fail, the code stops executing at that point and throws an Exception, which we catch harmlessly with except: pass. However, if it succeeds, the line after it runs, raising our complaining exception.