Flask learning (four)-WTF form

Project structure:
Insert picture description here

1. Original simple form verification:
app.py

from flask import Flask, render_template, request, flash

app = Flask(__name__)
app.secret_key = 'mgosdjg'

'''
flash:给模板传递消息
模板中需要遍历消息
需要对内容加密,因此需要设置secret_key,做加密消息的混淆
'''
@app.route('/', methods=['GET', 'POST'])
def hello_world():
    # request: 请求方式 --> 获取请求方式、数据

    # 1.判断请求方式
    if request.method == 'POST':
        # 2.获取请求的参数
        username = request.form.get('username')
        password = request.form.get('password')
        password2 = request.form.get('password2')

        # 3.判断参数是否填写 & 密码是否相同
        if not all([username, password, password2]):
            # return '参数不完整'
            flash(u'参数不完整')
        elif password != password2:
            # return '密码不一致'
            flash(u'密码不一致')
        else:
            return 'success'

    return render_template('index.html')


if __name__ == '__main__':
    app.run(host='192.168.235.128', port=5000, debug=True)

index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<form method="post">
    <label>用户名:</label><input type="text" name="username"><br>
    <label>密码:</label><input type="password" name="password"><br>
    <label>确认密码:</label><input type="password" name="password2"><br>
    <input type="submit" value="提交"><br>

    {
    
    # 使用遍历获取闪现的消息 #}
    {
    
    % for message in get_flashed_messages() %}
        {
    
    {
    
     message }}
    {
    
    % endfor %}
</form>

</body>
</html>

Effect:
Insert picture description here
2. Use WTF:
flask-wtf
Description: It is a library for form processing and verification, and provides functions such as csrf.
Installation: pip3 install flask-wtf
(1) Field type
Field type field description

  • StringField ordinary text field
  • SubmitField Submit
  • PasswordField Password field
  • TextAreaField Multi-line text field
  • DateField date field datetime.date
  • DateTimeFiled time period datetime.datetime
  • HiddenField Hidden Field
  • IntegerField numeric field
  • FloatField small number field
  • BooleanField bool field True and False
  • RadioFIeld radio field
  • SelectField drop-down field
  • FileField File upload field

(2) Verifier
Description of verifier name

  • DataRequired is required
  • Email verification email
  • IPAddress verify the ip address default ipv4
  • Length Verify the length min and max of the current value
  • NumberRange value range provides min and max
  • EqualTo verifies whether the values ​​of the two input boxes are the same
  • URL verification is a valid URL address
  • Regexp regular matching

app.py

from flask import Flask, render_template, request, flash
from flask_wtf import FlaskForm
from wtforms import StringField, PasswordField, SubmitField
from wtforms.validators import DataRequired, EqualTo

app = Flask(__name__)
app.secret_key = 'mgosdjg'

'''
flash:给模板传递消息
模板中需要遍历消息
需要对内容加密,因此需要设置secret_key,做加密消息的混淆
'''

'''
自定义WTF实现表单
自定义表单类
'''


class LoginForm(FlaskForm):
    username = StringField('用户名', validators=[DataRequired()])
    password = PasswordField('密码', validators=[DataRequired()])
    password2 = PasswordField('确认密码', validators=[DataRequired(), EqualTo('password', '密码填入的不一致')])
    submit = SubmitField('提交')

@app.route('/', methods=['GET', 'POST'])
def login():
    login_form = LoginForm()
    # 1.判断请求方式
    if request.method == 'POST':
        # 2.获取请求的参数
        username = request.form.get('username')
        password = request.form.get('password')
        password2 = request.form.get('password2')

        # 3.验证参数,WTF可以一句话就实现左右的校验
        # 注意前段加 csrf_token
        if login_form.validate_on_submit():
            return 'success'
        else:
            flash('参数有误')

    return render_template('index.html', form=login_form)


if __name__ == '__main__':
    app.run(host='192.168.235.128', port=5000, debug=True)

index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<form method="post">
    {
    
    {
    
     form.csrf_token() }}
    {
    
    {
    
     form.username.label }}{
    
    {
    
     form.username }} <br>
    {
    
    {
    
     form.password.label }}{
    
    {
    
     form.password }} <br>
    {
    
    {
    
     form.password2.label }}{
    
    {
    
     form.password2 }} <br>
    {
    
    {
    
     form.submit }}

    {
    
    # 使用遍历获取闪现的消息 #}
    {
    
    % for message in get_flashed_messages() %}
        {
    
    {
    
     message }}
    {
    
    % endfor %}
</form>

</body>
</html>

effect:
Insert picture description here

Guess you like

Origin blog.csdn.net/qq_34663267/article/details/111999541