其他分享
首页 > 其他分享> > 6、WTF表单验证

6、WTF表单验证

作者:互联网

1、main.py

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

app = Flask(__name__)

app.secret_key='suibian'

class LoginForm(FlaskForm):
    username = StringField(u"用户名:",validators=[DataRequired()])
    password = PasswordField(u'密码:',validators=[DataRequired()])
    password2 = PasswordField(u'确认密码:',validators=[DataRequired(),EqualTo('password','密码错误')])
    submit = SubmitField(u'提交:')

@app.route('/',methods=['GET','POST'])
def loging():
    logings = LoginForm()
    if request.method=='POST':
        username = request.form.get('username')
        password = request.form.get('password')
        password2 = request.form.get('password2')
        if logings.validate_on_submit():
            print(username,password,password2)
            return "success"
        else:
            flash("参数有误")
    return render_template('myhtml.html',forms = logings)
if __name__=='__main__':
    app.run()

2、myhtml.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>flask框架测试</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>
<br>
<form method="post">
    {{forms.csrf_token()}}
    {{forms.username.label}}{{forms.username}}<br>
    {{forms.password.label}}{{forms.password}}<br>
    {{forms.password2.label}}{{forms.password2}}<br>
    {{forms.submit}}<br>
</form>
</body>
</html>

标签:__,username,password2,验证,request,表单,forms,WTF,password
来源: https://blog.csdn.net/qq_15060477/article/details/121721089