The FLASK-WTF extension can turn the process of working with Web Forms into a pleasurable experience.
One, cross-site request forgery protection
By default, FLASK-WTF is able to protect all forms from cross-site request forgery attacks. A malicious website can cause a CSRF attack when it sends a request to a website that the attacker has logged on to.
In order to achieve CSRF protection, FLASK-WTF requires the program to set a key. FLASK-WTF uses this key to generate an encrypted token, and then uses the token to verify the authenticity of the form data in the request. The method for setting the key is as follows:
App = Flask (__name__) app.config[' Secret_key ']= ' hard to guess string '
Second, form category
When using FLASK-WTF, each Web form is represented by a class that inherits from the form. This defines a set of fields in the form that each field is represented by an object. A Field object can have one or more validation functions attached to it. The validation function is used to verify that the input values submitted by the user meet 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's your name? ', Validators=[required ()]) submit = Submitfield (' Submit ')
The Stringfield class represents the <input> element with the property type= "text", and the Submitfield class represents the <input> element with the property type= "Submit".
Wtforms Supported HTML standard fields
Field type |
Description |
Stringfield |
Text field |
Textareafield |
Multi-line Text field |
Passwordfield |
Password text field |
HiddenField |
Hide text fields |
Datefield |
Text field with a value of datetime.date format |
Integerfield |
Text field with a value of integer |
Floatfield |
Text field, value is floating point |
Selectfield |
drop-down list |
Submitfield |
Form Submit button |
Wtforms validation function
Validation functions |
Description |
Email |
Verify e-mail address |
Equalto |
Compare the values of two fields, often used to require a two password for confirmation |
IPAddress |
Verifying the IPV4 network address |
Length |
Verify the length of the input string |
Numberrange |
Verify that the value entered is within the range of numbers |
Optional |
Skip other validation functions when no input value |
Required |
Make sure there is data in the field |
Regexp |
Validating an input value using regular expressions |
Url |
Verify URL |
AnyOf |
Make sure the input value is in the list of optional values |
Noneof |
Make sure the input value is not in the optional values list |
D. Render the form into HTML
form fields are available, and are rendered as HTML after they are called in the template. Suppose a view function passes a Nameform instance through a parameter form into a template, a simple form can be generated in the template, as shown here:
<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 renders the entire FLASK-WTF form with a pre-defined form style in the bootstrap, which can be done only once in a single call.
{% import "boostrap/wtf.html" as WTF%} {{wtf.quick_form (form)}}
#使用Flask-WTF and flask-bootstrap render form {% extends "base.html"%}{% import "bootstrap/wtf.html" as WTF%}{% block title%}flasky{ % endblock%}{% block page_content%}<div class= "Page-header" >
Iv. working with 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 the App.route decorator tells Flask to register this view function as a handler for Get and post requests in the URL map. If you do not specify the methods parameter, only the view function is registered as a handler for the GET request.
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 '))
Six, Flash messageExample: Prompt user name or password error, popup window
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 '))
#渲染Flash消息 {% block content%}<div class= "container" > {% for message in get_flashed_messages ()%} <div class= "Alert alert-warning" > <button type= "button" class= "Close" data-dismiss= "alert" >x</button > {message}} </div> {% endfor%} {% block page_content%}{% Endblock%}</div>{% Endblock%}
Python flask-web Form