from wtforms import Formfrom flask import Flask,render_template,request,redirectfrom wtforms.fields import corefrom wtforms.fields import html5from wtforms.fields import simplefrom wtforms import validatorsfrom wtforms import widgetsimport sysreload(sys)sys.setdefaultencoding('utf8')#python2.7 转码用的,避免显示中文为乱码app = Flask(__name__,template_folder='templates')app.debug=Trueclass LoginForm(Form): name = simple.StringField( label='用户名', #前端显示中文 validators=[ validators.DataRequired(message='用户名不能为空'), validators.Length(min=6,max=18,message='用户名长度必须大于%(min)d且小于%(max)d') ], #字段的验证规则 widget=widgets.TextInput(), #页面上显示的标签 render_kw={'class':'form=control'} #给上面插件生成的时候添加属性,比如bootstrap的属性 ) pwd = simple.PasswordField( label='密码', validators=[ validators.DataRequired(message='密码不能为空'), validators.Length(min=8,message='用户名长度必须大于%(min)d'), validators.Regexp(regex="^(?=.*[a-z])(?=.*[A-Z])(?=.*/d)(?=.*[$@$!%*?&])[A-Za-z/d$@$!%*/&]{8,}", message='密码至少8个字符,至少1个大写字母,1个小写字母'), ], widget=widgets.PasswordInput(), render_kw={'class':'from-control'} )#字段,内部包含正则表达式@app.route('/login',methods=['GET','POST'])def login(): if request.method == 'GET': form = LoginForm() return render_template('login.html',form=form) #将form对象传给前端 else: form = LoginForm(formdata=request.form) #从请求体from中取值 if form.validate(): #验证 print "用户提交数据通过,提交的值为:",form.data else: print form.errors #错误信息 return render_template('login.html',form=form)@app.route('/')def hello_world(): return 'Hello World!'if __name__ == '__main__': app.run()
<!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <meta http-equiv="x-ua-compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>Title</title></head><body><h1>登陆</h1><form method="post"> <p>{{ form.name.label }} {{ form.name }} {{ form.name.errors[0] }}</p> <p>{{ form.pwd.label }} {{ form.pwd }} {{ form.pwd.errors[0] }}</p> <input type="submit" value="提交"></form></body></html>