这个库一般有两个作用。第一个就是做表单验证,把用户提交上来的数据进行验证是否合法。第二个就是做模版渲染。
# coding:utf-8
from flask import Flask, request, render_template
from wtforms import Form, StringField, PasswordField, SubmitField
from wtforms.validators import Length, DataRequired, EqualTo
class RegistForm(Form):
username = StringField(u'用户名', validators=[DataRequired(), Length(3, 10, message=u'请输入3-10位的用户名')])
password = PasswordField(u'密码', validators=[DataRequired(), Length(6, 10)])
password2 = PasswordField(u'重复密码', validators=[DataRequired(), EqualTo('password')])
submit = SubmitField(u'注册')
app = Flask(__name__)
@app.route('/')
def hello_world():
return 'Hello World!'
@app.route('/regist/', methods=['GET', 'POST'])
def regist():
if request.method == "GET":
return render_template('regist.html')
else:
form = RegistForm(request.form)
if form.validate():
return u'注册成功'
else:
print form.errors
return u'注册失败'
if __name__ == '__main__':
app.run(debug=True)
数据发送过来,经过表单验证,因此需要验证器来进行验证,以下对一些常用的内置验证器进行讲解:
代码示例如下:
class LoginForm(Form):
email = StringField(validators=[Email(), ])
username = StringField(validators=[InputRequired()])
age = IntegerField(validators=[NumberRange(12, 100)])
phone = StringField(validators=[Regexp(r'1[34578]\d{9}')])
url = StringField(validators=[URL()])
uuid = StringField(validators=[UUID()])
如果想要对表单中的某个字段进行更细化的验证,那么可以针对这个字段进行单独的验证。步骤如下:
validate_字段名(self,filed)
。field.data
可以获取到这个字段的具体的值。wtforms.validators.ValidationError
的异常,并且把验证失败的信息传到这个异常类中。class LoginForm(Form):
email = StringField(validators=[Email(), ])
username = StringField(validators=[InputRequired()])
age = IntegerField(validators=[NumberRange(12, 100)])
phone = StringField(validators=[Regexp(r'1[34578]\d{9}')])
url = StringField(validators=[URL()])
# uuid = StringField(validators=[UUID()])
captcha = StringField(validators=[Length(4, 4)])
# 自定义验证
def validate_captcha(self, field):
if field.data != '1234':
raise ValidationError(u'validate error!')