Chapter 4. Web Forms
The request object, introduced in Chapter 2, exposes all the information sent by the client with a request. In particular, request.form provides access to form data submitted in POST requests.
Although the support provided in Flask’s request object is sufficient for the handling of web forms, there are a number of tasks that can become tedious and repetitive. Two good examples are the generation of HTML code for forms and the validation of the submitted form data.
The Flask-WTF extension makes working with web forms a much more pleasant experience. This extension is a Flask integration wrapper around the framework-agnostic WTForms package.
Flask-WTF and its dependencies can be installed with pip:
(venv)$pip install flask-wtf
Cross-Site Request Forgery (CSRF) Protection
By default, Flask-WTF protects all forms against Cross-Site Request Forgery (CSRF) attacks. A CSRF attack occurs when a malicious website sends requests to a different website on which the victim is logged in.
To implement CSRF protection, Flask-WTF needs the application to configure an encryption key. Flask-WTF uses this key to generate encrypted tokens that are used to verify the authenticity of requests with form data. Example 4-1 shows how to configure an encryption key.
app=Flask(__name__)app.config['SECRET_KEY']='hard to guess string'
The app.config dictionary is a general-purpose place to store configuration variables used by the framework, the ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access