当前位置:网站首页>Flask framework - flask WTF form: data validation, CSRF protection
Flask framework - flask WTF form: data validation, CSRF protection
2022-07-25 10:53:00 【White chocolate Lin】
Catalog
In the previous document , We learned Flask frame —— The news flashed , This article is for us to learn Flask frame ——Flask-WTF Forms : data validation 、CSRF Protect .
Flask-WTF
Forms are responsible for collecting data from web pages , yes Web Basic functionality of the application .
Flask-WTF yes Flask An extension of the framework , Used to process forms , It encapsulates the WTForms, Its characteristics are :
Can quickly define form templates ;
Validate form data ;
Overall csrf Protect , It can protect all forms from Cross Site Request Forgery (CSRF) The attack of ;
And Flask-Uploads Support file uploading together ;
International integration .
stay WTForm In the form , The main function is to verify the legitimacy of the data submitted by users 、 Fast rendering templates 、CSRF Protect 、 File upload and verification code .
Its installation method is very simple , Execute the following code :
pip install flask-wtf
In the installation flask-wtf In the process of , The system will install automatically wtform.
WTForms
form field
WTforms The package contains definitions of various form fields ,WTForms Support HTML The fields for are :
| Field | explain |
|---|---|
| BooleanField | Check box , The value is True or False, amount to HTML Of |
| DateField | The text field , The value is datetime.date Format |
| DateTimeField | The text field , The value is datetime.datetime Format |
| IntegerField | The text field , The value is integer. |
| DecimalField | Text field for displaying numbers with decimals , The value is decimal.Decimal |
| FloatField | The text field , The value is a floating-point number |
| RadioField | A set of menus |
| FileField | File upload field |
| SelectField | The drop-down list |
| SelectMultipleField | The drop-down list , Multiple values can be selected |
| SubmitField | Form submit button , amount to HTML Of |
| StringField | The text field , amount to HTML Of |
| TextAreaField | Multiline text fields , amount to HTML Of |
| HiddenField | Hide text fields , Quite a HTML Of |
| FormFiled | Embed another form field |
| FieldList | Subgroup specifies the type of field |
| PasswordField | Password text field , amount to HTML Of |
validators Validator
WTForms Supported by validators The verifier has :
| Validation function | explain |
|---|---|
| Verification is an email address | |
| EqualTo | Compare the values of two fields ; It is often used in the case that the information is required to be input twice for confirmation |
| IPAddress | verification IPv4 network address |
| Length | The length of the input string |
| NumberRange | Verify that the value entered is in the numeric range |
| Optional | Skip other validation functions when there is no input value |
| DataRequired | Make sure there is data in the field |
| Regexp | Use regular expressions to validate input values |
| URL | verification 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 list |
Be careful : Use the above WTForms Forms support HTML Fields and validation functions , You need to import these HTML Fields and validation functions
Okay , I understand WTForms Forms support HTML Fields and validation functions , Next, we will demonstrate form data validation through example code .
data validation
Create a Flask Project and create a project named form.py Form class file , Of course, the file name can be arbitrary , stay form.py Write the following code in the file :
from flask_wtf import FlaskForm # Import FlaskForm
from wtforms import StringField, PasswordField # Import the required fields
from wtforms.validators import DataRequired, length # Import the required validation function
class MyForm(FlaskForm):
name = StringField('name', validators=[DataRequired()]) # Use text fields , Data cannot be null validation
password=PasswordField('password',validators=[DataRequired(),length(min=6,max=12)]) # Use the password text field ,length Length verification
Import what we need FlaskForm、 Fields and validation functions , Here we use StringField、PasswordField Fields and DataRequired Data cannot be empty validation function 、length Length verification function .
Of course, we can add multiple validation functions in the field , Only need validators Add a verification function to the verifier , for example : take name = StringField('name', validators=[DataRequired()]) Change the code to :
name = StringField('name', validators=[DataRequired(),length(min=2,max=6)])
The form file has been written , And then templates Create a directory called form Of html file , And then in Flask Project app.py Write the view function in the file , The code is as follows :
from flask import Flask, render_template
from form import MyForm
app = Flask(__name__)
@app.route('/')
def user_form():
myform=MyForm() # Create form class objects
if myform.validate_on_submit():
return ' Submit successfully '
return render_template('form.html',myform=myform) # Rendering form.html, And will myform The form object is transferred to form.html in
if __name__ == '__main__':
app.run()
Import the necessary packages and libraries , Create the form class object just written in the view function myform,validate_on_submit() Method to check whether it is a POST Request and whether the request is valid , Re pass render_template() Method rendering form.html file , And will myform Pass in form.html in .
app.py The view function in the file has been written , Next, write the just created form.html file , The file code is as follows :
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
{# create form #}
<form action="" method="post">
<p>{
{ myform.name }}</p>
<p>{
{ myform.password }}</p>
<p>{
{ myform.submit }}</p>
</form>
</body>
</html>
stay form.html In file , We go through { { Form class object . attribute }} Render form fields , When we pass in the form class field definition label When parameters are , You can also use { { Form class object . attribute .label }} Render the label Text .
Is this ok , We run Flask project , Browser access http://127.0.0.1:5000/, The following errors were reported :
RuntimeError: A secret key is required to use CSRF. # Runtime error : Use CSRF Key required
At this time, we only need to add SECRET_KEY that will do , The code is as follows :
app.config['SECRET_KEY']='hakhfaskh' #SECRET_KEY Value is arbitrary
Restart Flask Project and browse http://127.0.0.1:5000/ It won't be wrong , As shown in the figure below :

When we don't enter information and press submit , The system will automatically prompt the built-in error prompt of the browser .
Look at the source code , Can be found, can be found WTForm The first parameter of the form field is id and name Value .
Custom validation
Generally speaking , If there is additional validation required for the form , Generally, you can customize the additional verification method of the form instead of re customizing the new fields , We can go through form.py Used in form classes validate_ Custom validation , The sample code is as follows :
def validate_name(self,data): # by name Add custom validata_%s, And pass in the input value data
if self.name.data[0].isdigit(): # Use isdigit Check whether it starts with a number , Use data[0] Get the first place of data
raise ValidationError(' User name cannot start with a number ') # If the verification fails, an exception will be thrown
Here we are form.py In the form class name Add custom validation , So the custom function is called validate_name, If we are in the form class password When adding custom validation , The custom function is named validate_password, That is to say, the name of the user-defined verification function should correspond to the field name in the form class .
Here we add the authentication that the user name cannot start with a number , start-up flask project , And access http://127.0.0.1:5000/, As shown in the figure below :

CSRF Protect
In the above operation , It's not used yet CSRF Protect , In the use of CSRF Before protection , Let's get to know CSRF Some knowledge of .
CSRF: Cross-site request forgery (Cross—Site Request Forgery), Follow XSS The attack is the same , There is great harm .
Simply put, hackers have stolen your identity , Send malicious requests in your name , The server doesn't know that it was requested by the hacker , The server thinks it's your request .
The attack principle is shown in the figure below :

User Xiao Ming enters the user name 、 Password login to a secure website A, The website server returns through authentication information cookie To the user's browser , Before exiting the website A Or delete cookie period , Xiao Ming browsed a bad website B, Bad websites B Attack code to get your secure website A Of cookie Value and visit the website A, Because hackers own Xiaoming website A Of cookie, You can visit the website as Xiao Ming A, Send an email in the name of Xiao Ming 、 Send a message , Stealing your account , Add system administrator , Even buying goods 、 Virtual currency transfer and other operations .
Many online frauds are CSRF attack , So don't casually click on links with unknown origins and don't browse bad websites .
So how to defend CSRF Attack ?
stay Flask In the project , Use CSRFProtect() Method start global enable CSRF Protect , The code is as follows :
from flask import Flask, render_template
from flask_wtf import CSRFProtect
from form import MyForm
app = Flask(__name__)
app.config['SECRET_KEY']='hakhfaskh'
# start-up CSRF Protect
csrf = CSRFProtect(app)
@app.route('/',methods=['GET','POST'])
def hello_world():
myform=MyForm() # Create form class objects
return render_template('form.html',myform=myform)
if __name__ == '__main__':
app.run()
CSRF Protection requires a key ,CSRF The default is to use the configured SECRET_KEY value , Of course, we can also use it alone WTF_CSRF_SECRET_KEY To set up .
stay HTML In file , We need to render csrf_token Or use <input type="hidden" To hide csrf_token The code is as follows :
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<form action="" method="post">
{
{ myform.csrf_token }} {# Rendering csrf_token#}
{# Use <input type="hidden" hide csrf_token#}
{# <input type="hidden" name="csrf_token" value="{
{ csrf_token() }}"/>#}
<p>{
{ myform.name }}</p>
<p>{
{ myform.password }}</p>
<p>{
{ myform.submit }}</p>
</form>
</body>
</html>
In this way, it is successfully used CSRF Protect , start-up Flask Project and visit http://127.0.0.1:5000/, As shown in the figure below

When we fill in the information in the form of the website, we will carry the hidden value and submit it to the server , The server returns according to the hidden value and the information filled in by the user cookie Value to the user , and cookie Value has no hidden value information , Even if hackers get our cookie value , But cannot get the hidden value , Without hidden values, the information verification of the server cannot be obtained . So that CSRF Protect 、 Data security .
Okay , About Flask frame ——Flask-WTF Forms : data validation 、CSRF That's all for protection , Thank you for watching. , Next article study Flask frame ——Flask-WTF Forms : Upload files 、 Verification Code .
official account : White chocolate LIN
The official account is released Python、 database 、Linux、Flask、 automated testing 、Git Etc !
- END -
边栏推荐
- 3. Like you, DNS domain name resolution service!!!
- Redis usage scenario
- Acquisition and compilation of UE4 source code
- 10. Expect interaction free
- HCIA实验(09)
- 云原生IDE:iVX免费的首个通用无代码开发平台
- Upgrade glibc 2.29 checking LD_ LIBRARY_ Path variable... Contains current directory error solution
- 美国机场围棋风格可视化专题图:ArcGIS Pro版本
- Flask框架——消息闪现
- Hucang integrated e-commerce project (II): project use technology, version and basic environment preparation
猜你喜欢

Using px2rem does not take effect

11.iptables 防火墙

2021 CEC written examination summary

Introduction to onnx (open neural network exchange)

4.FTP服务配置与原理

Attention is all you need paper intensive reading notes transformer

Hucang integrated e-commerce project (II): project use technology, version and basic environment preparation
C# 类库的生成,使用类库对象对DataGridView 进行数据绑定

【策略模式】就像诸葛亮的锦囊

Visual thematic map of American airport go style: ArcGIS Pro version
随机推荐
Flask框架——Flask-WTF表单:文件上传、验证码
Basic experiment of microwave technology - Filter Design
异步Servlet在转转图片服务的实践
4.FTP服务配置与原理
Pytorch tensor list is converted to tensor list of tensor to tensor using torch.stack()
AI technology stack is too huge! Wu Enda gives career planning: lifelong learning
4.隔壁小孩都会的,各种shell符号{}[]等
UE4 quickly find the reason for packaging failure
How to connect tdengine through open source database management tool dbeaver
【信息系统项目管理师】思维导图系列精华汇总
Using numpy for elevation statistics and visualization
Attention is all you need paper intensive reading notes transformer
使用Three.js实现炫酷的赛博朋克风格3D数字地球大屏
QT | mouse events and wheel events qmouseevent, qwheelevent
HCIP(11)
3.跟你思想一样DNS域名解析服务!!!
HCIA实验(10)NAT
信号完整性(SI)电源完整性(PI)学习笔记(三十四)100条估计信号完整性效应的经验法则
云原生IDE:iVX免费的首个通用无代码开发平台
Pytoch separates tensor by the value of one dimension of tensor (simple)