当前位置:网站首页>Flask learning and project practice 9: WTF form verification

Flask learning and project practice 9: WTF form verification

2022-07-06 03:36:00 Study notes of Zhou

1.WTF Introduction to form validation

Flask-WTF It's simplified WTForms A third-party library for operations .WTForms The two main functions of the form are to verify the legitimacy of the data submitted by the user and render the template . Of course, it also includes some other functions :CSRF Protect , File upload, etc . install Flask-WTF It will also be installed by default WTForms, So use the following command to install Flask-WTF: pip install flask-wtf.

For example, log in when you go to Taobao , First check whether the user input meets the conditions , If you are not satisfied, you will not check the database . namely Verify whether the requirements are met before querying the database .

WTForms It can also be used in other frameworks , Such as django etc. . and Flask This third-party library is specially simplified , To facilitate the operation of the project .

2. Perform form validation

validators Just pass some validation parameters in for comparison .

The code is as follows :

class RegistForm(Form):
    name = StringField(validators=[length(min=4,max=25)])
    email = StringField(validators=[email()])
    password = StringField(validators=[DataRequired(),length(min=6,max=10),EqualTo('confirm')])
    confirm = StringField()

DataRequired It means that the password must be entered ,EqualTo(‘confirm’) Must be equal .

3. Code implementation

 Insert picture description here
stay action Which means , When the button is clicked , To which url.

method It refers to the request method . And also notice that input Of name It needs to correspond to your own settings .

 Insert picture description here
 Insert picture description here
If the authenticator of the mailbox is missing , have access to pip install email_validator To install .

At the same time, the above code needs to be improved , That is, for views, only GET, Need to increase the post As shown in the figure below :
 Insert picture description here
 Insert picture description here
So you can verify .( Initially relieve the pressure on the database ).

原网站

版权声明
本文为[Study notes of Zhou]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/02/202202132315076870.html