Exploring the Flask web framework in Python
The Application
The application consists of the forms, models, and views in the app.py
file (Listing 2). The first step is to import the necessary modules (lines 1 to 9). The Flask extensions mentioned above, such as SQL Alchemy [11] and Bootstrap [9], help to manage the database. As of line 11, the script creates several objects.
Listing 2
Import and Object Building
Models
The database consists of the two tables, users
and ideas
. For users, the application only stores a hash of the password in the users
class (Listing 3) and checks it later. The application does not store passwords in clear text but generates a secure hash via the werkzeug.security.generate_password_hash()
feature and verifies hashes with werkzeug.security.check_password_hash()
. Werkzeug, a central component of Flask, provides both of these features. The Idea
class (Listing 4) takes care of the ideas. Idea
contains a reference to the user who created the idea, so Geistesblitze only shows the user their own flashes of genius next time up.
Listing 3
User Management
Listing 4
Collecting Ideas
Checking Forms
WT-Forms [13] generates three forms. The form framework defines the forms and also takes care of their validation.
Thanks to the WT-Forms RegisterForm
(Listing 5), WT-Forms does not just check whether the two given passwords are the same, but also whether the username already exists in the database. The minimum length of the user name and password could be checked in this way, once the user is registered. Similar content validation checks are performed by the LoginForm
and AddIdeaForm
classes.
Listing 5
Form Validation
« Previous 1 2 3 Next »
Buy this article as PDF
(incl. VAT)