WTForms表单验证
flask-WTF
- 为了方便演示我们创建一个py文件
from flask import Flask,request,render_template
app = Flask(__name__)
@app.route('/')
def index():
return '首页'
@app.route('/regist/',methods = ['GET','POST'])
def regist():
if request.method == 'GET':
return render_template('regist.html')
else:
username = request.form.get('username')
password = request.form.get('password')
password_verify = request.form.get('password_verify')
if len(username)<3 or len(username)>10:
return '用户名长度不正确'
if password != password_verify:
return '两次密码不一致'
if len(password)<3 or len(password)>10:
return '密码长度不正确'
if __name__ =='__main__':
app.run(debug=True,port=8888)
- 和regist.html文件
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<form action="" method="post"></form>
用户名:<input type="text" name="username"><br>
密码:<input type="text" name="password"><br>
确认密码:<input type="text" name="password_verify"><br>
<input type="submit" value="注册">
</body>
</html>
- 可以看到我们上面要对我们注册的用户进行判断非常麻烦
- 所以我们使用flask-wtf库
- 首先需要安装库,安装之后
- 创建一个新的forms.py文件,直接在其中进行判断,min最小值,max最大值,不满足前两个输出message的值
from wtforms import Form,StringField
from wtforms.validators import Length,EqualTo
# 表单验证
class RegistFrom(Form):
username = StringField(validators=[Length(min=3,max=10,message='用户名长度不正确')])
password = StringField(validators=[Length(min=3,max=10,message='密码长度不正确')])
password_verify = StringField(validators=[EqualTo('password',message='两次密码不一致')])
- 我们视图函数文件中应该改为这样
from flask import Flask,request,render_template
from forms import RegistFrom
app = Flask(__name__)
@app.route('/')
def index():
return '首页'
@app.route('/regist/',methods = ['GET','POST'])
def regist():
if request.method == 'GET':
return render_template('regist.html')
else:
form = RegistFrom(request.form)
if form.validate():
return '注册成功'
else:
print(form.errors)
return '注册失败'
if __name__ =='__main__':
app.run(debug=True,port=8888)
- 如果有需要进行验证的直接在forms.py进行添加即可