Python Flask-web form, pythonflask-web
The Flask-WTF extension turns the process of processing web forms into a pleasant experience.
I. Cross-Site Request Forgery Protection
By default, Flask-WTF can protect all forms from cross-site request forgery attacks. When a malicious website sends a request to a website that has been logged on by an attacker, it will cause a CSRF attack.
To implement CSRF protection, Flask-WTF requires a program to set a key. Flask-WTF uses this key to generate an encryption token, and then uses the token to verify the authenticity of the form data in the request. You can set the secret as follows:
app = Flask(__name__)app.config['SECRET_KEY']='hard to guess string'
Ii. Form
When Flask-WTF is used, each web Form is represented by a Class inherited from the Form. This defines a group of fields in the form. Each field is represented by an object. The Field object can attach one or more verification functions. The verification function is used to verify that the input value submitted by the user meets the requirements.
#! /Usr/bin/env python # a simple web form that contains a text field and a submit button from flask_wtf import Formfrom wtforms import StringField, SubmitFieldfrom wtforms. validators import Requiredclass NameForm (Form): name = StringField ('What is your name? ', Validators = [Required ()]) submit = SubmitField ('submit ')
The StringField class indicates the <input> element whose property is type = "text", and the SubmitField class indicates the <input> element whose property is type = "submit.
Standard HTML fields supported by WTForms
Field Type |
Description |
StringField |
Text Field |
TextAreaField |
Multi-line text fields |
PasswordField |
Password text field |
HiddenField |
Hide text fields |
DateField |
Text Field in the datetime. date Format |
IntegerField |
Text Field with an integer value |
FloatField |
Text Field, value: Floating Point |
SelectField |
Drop-down list |
SubmitField |
Form submission button |
WTForms verification function
Verify the Function |
Description |
Email |
Verify email address |
Similar |
Compares the values of two fields. It is often used when two passwords are required for confirmation. |
IPAddress |
Verify IPv4 network address |
Length |
Verify the length of the input string |
NumberRange |
Verify that the entered value is within the Numerical range |
Optional |
Skip other verification functions if no value is input |
Required |
Make sure there is data in the field |
Regexp |
Use regular expressions to verify input values |
URL |
Verify URL |
AnyOf |
Make sure that the input value is in the optional value list. |
NoneOf |
Make sure that the input value is not in the optional value list. |
4. render the form into HTML
Form fields are available and rendered as HTML after being called in the template. Assume that the view function passes a NameForm instance to the template through the form parameter. A simple form can be generated in the template, as shown below:
<form method="POST"> {{ form.hidden_tag() }} {{ form.name.label }} {{ form.name() }} {{ form.submit() }}</form>
<form method="POST"> {{ form.hidden_tag() }} {{ form.name.label }} {{ form.name(id='my-text-field') }} {{ form.submit() }}</form>
Flask-Bootstrap provides a very high-end helper function that uses the predefined form style in Bootstrap to render the entire Flask-WTF form. These operations can be completed only once by calling them.
{% import "boostrap/wtf.html" as wtf %}{{ wtf.quick_form(form) }}
# Use Flask-WTF and Flask-Bootstrap to render the FORM {% extends "base.html" % }{% import "bootstrap/wtf.html" as wtf % }{% block title %} Flasky {% endblock % }{% block page_content %} <div class = "page-header">
4. process forms in view Functions
@app.route('/',methods=['GET','POST'])def index(): name = None form = NameForm() if form.validate_on_submit(): name = form.name.data form.name.data = '' return render_template('index.html',form=form,name=name)
The methods parameter added in app. route modifier tells Flask to register this view function as the GET and POST request handler in URL ing. If the methods parameter is not specified, the view function is registered as the GET request handler.
V. redirection and user sessions
#!/usr/bin/env pythonfrom flask import Flask,render_template,session,redirect,url_forapp = Flask(__name__)@app.route('/',methods=['GET','POST'])def index(): form = NameForm() if form.validate_on_submit(): session['name'] = form.name.data return redirect(url_for('index')) return render_template('index.html',form=form,name=session.get('name'))
6. Flash messages
Example: The user name or password is incorrect. The pop-up window appears.
from flask import Flask,render_template,session,redirect,url_for,flashapp = Flask(__name__)@app.route('/',methods=['GET','POST'])def index(): form = NameForm() if form.validata_on_submit(): old_name = session.get('name') if old_name is not None and old_name != form.name.data: flash('Looks like you have changed your name!') session['name'] = form.name.data return redirect(url_for('index')) return render_template('index.html',form=form,name=session.get('name'))
# Rendering Flash message {% block content %} <div class = "container" >{% for message in get_flashed_messages () %} <div class = "alert-warning"> <button type = "button" class = "close" data-dismiss = "alert" >×</button> {{ message }}</div >{% endfor % }{% block page_content %}{% endblock %}</div >{% endblock %}