6.Flask-WTForms
Flask-WTF是简化了WTForms操作的一个第三方库。WTForms表单的两个主要功能是验证用户提交数据的合法性以及渲染模板。还有其它一些功能:CSRF保护,
文件上传等。安装方法:pip install flask-wtf
1.1.WTForms简单验证
from flask import Flask,request,render_template from wtforms import Form,StringField from wtforms.validators import Length,EqualTo app = Flask(__name__) class RegistForm(Form): username = StringField(validators=[Length(min=3,max=10,message='用户名必须在3到10位之间')]) password = StringField(validators=[Length(min=6,max=10,message='密码必须6到10位之间')]) password_repeat = StringField(validators=[Length(min=6,max=10), EqualTo("password",message='密码不一致')]) @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 'success' else: print(form.errors) return 'fail' if __name__ == '__main__': app.run()
1.2.WTForms常用验证器和自定义验证器
常用的验证器
- Email:验证上传的数据是否为邮箱格式
- EqualTo:两个字段是否相等(密码和重复密码)
- InputRequired:原始数据的需要验证
- Length:长度限制,有mix和max两个值
- NumberRange:数字的区间,有mix和max两个值,如果在两个值之间则满足
- Regexp:自定义正则表达式
- URL:必须url格式
- UUID:uuid格式
from wtforms import Form,StringField,IntegerField from wtforms.validators import Length,EqualTo,Email,InputRequired,NumberRange from wtforms.validators import Regexp,URL,ValidationError class LoginForm(Form): email = StringField(validators=[Email(message='邮箱格式不正确')]) username = StringField(validators=[InputRequired(message='这个字段必须要填')]) age = IntegerField(validators=[NumberRange(min=18,max=100)]) phone = StringField(validators=[Regexp(r'1[38745]\d{9}')]) homepage = StringField(validators=[URL()]) captcha = StringField(validators=[Length(4,4)]) # 自定义验证器 def validate_captcha(self,field): if field.data != '1234': #field.data:用户提交过来的数据 raise ValidationError('验证码错误') #如果验证失败,就抛出验证失败的异常
1.3.使用wtforms渲染模板
forms.py
class SettingsForm(Form): username = StringField(label="用户名:",validators=[InputRequired(message='这个字段必须要填')]) age = IntegerField('年龄:',validators=[NumberRange(min=18, max=100)]) remeber = BooleanField('记住我') tags = SelectField('标签',choices=[(1,'python'),(2,'django')])
flask_wtforms_demo.py
@app.route('/settings/',methods=['GET','POST']) def settings(): if request.method == 'GET': form = SettingsForm() return render_template('settings.html',form=form) else: pass
settings.html
<form action="" method="post"> {# 括号里面可以添加样式#} <p>{{ form.username.label }} {{ form.username(class="") }}</p> <p>{{ form.age.label }} {{ form.age() }}</p> <p>{{ form.remeber.label }} {{ form.remeber() }}</p> <p>{{ form.tags.label }} {{ form.tags() }}</p> <p><input type="submit" value="提交"></p> </form>
皮豆设计(logo设计神器):http://pidou.cn