|
在Web应用中,表单处理是一个基本而常见的任务。Python的WTForms库通过提供表单的结构、验证和渲染等功能,简化了表单的处理流程。与此同时,Flask的扩展Flask-WTF更进一步地整合了WTForms,为开发者提供了更便捷、灵活的表单处理方式。Flask-WTF是建立在WTForms之上的Flask扩展,旨在简化Web应用中表单处理的流程。它提供了与Flask框架的无缝集成,使得表单的创建、验证和渲染变得非常容易。通过Flask-WTF,开发者能够轻松地构建具有强大功能和良好用户体验的表单页面。
主要特点:
- 结合WTForms功能: Flask-WTF基于WTForms库,继承了WTForms的强大功能,包括表单字段、验证器等,为开发者提供了一套完备的表单处理工具。
- Flask集成: 与Flask框架无缝集成,通过简单的导入和初始化,即可在Flask应用中使用Flask-WTF提供的表单处理功能。
- CSRF保护: Flask-WTF内置了CSRF(Cross-Site Request Forgery)保护机制,帮助开发者防范Web应用中的CSRF攻击。
- 表单渲染: 提供了方便的表单渲染方法,使得表单的呈现过程更为简单,开发者可以轻松定制表单的外观。
- 文件上传支持: 支持文件上传功能,使得开发者能够方便地处理包含文件上传功能的表单。
通过Flask-WTF,开发者能够以更高效的方式处理Web应用中的表单,减少重复性工作,提升开发效率。
简单验证表单
前台定义渲染模板,后端对模板渲染,并根据validators验证器中的规则对输入内容进行匹配。- <form method="post">
- {{ form.csrf_token }}
-
- <p>{{ form.username.label() }} : {{form.username}}</p>
- <p>{{ form.password.label }} : {{form.password}}</p>
- <p>{{ form.repeat_password.label }} : {{form.repeat_password}}</p>
- {% for msg in form.repeat_password.errors %}
- <p>提示: {{msg}}</p>
- {% endfor %}
- {{form.submit}}
- </form>
复制代码 后台定义MyFlaskForm(FlaskForm)类用于对登录表单进行动态渲染。- from flask import Flask, render_template, request
- from flask_wtf import FlaskForm
- from wtforms import StringField, PasswordField, SubmitField
- from wtforms.validators import DataRequired, EqualTo,Length,Regexp
- app = Flask(__name__)
- app.config["SECRET_KEY"] = "d3d3Lmx5c2hhcmsuY29t"
- # 定义表单模型类
- class MyFlaskForm(FlaskForm):
- # DataRequired 验证不为空,Length 限制长度, Regexp限制不允许出现弱口令
- username = StringField(label=u"登录账号", validators=[DataRequired(), Length(min=6, max=18)])
- password = PasswordField(label=u"登录密码", validators=[DataRequired(), Length(min=6, max=18)])
- repeat_password = PasswordField(label=u"确认密码", validators=[DataRequired(),EqualTo("password", u"两次密码不一致")])
- submit = SubmitField(label=u"提交")
- @app.route("/", methods=["GET", "POST"])
- def index():
- form = MyFlaskForm()
- if request.method == "POST":
- if form.validate_on_submit():
- username = form.username.data
- password = form.password.data
- repeat_password = form.repeat_password.data
- print("用户名: {} --> 密码: {}".format(username,repeat_password))
- return render_template("index.html", form=form)
- return render_template("index.html", form=form)
- if __name__ == '__main__':
- app.run(debug=True)
复制代码 运行后默认构造一个账号密码登录窗口的表单,用户可以填写表单并返回给后台信息,如下图所示;
表单附加参数
所谓附加参数就是指,渲染器返回页面是主动对某个组件增加一些CSS属性,这些属性起到装饰作用,通常会使用render_kw属性返回CSS。- {% for msg in get_flashed_messages() %}
- <p>闪现消息: {{ msg }}</p>
- {% endfor %}
- <form method="POST" id="form-data">
- {{ form.csrf_token }}
- {{ form.username.label }} : {{ form.username }}
- {{ form.password.label }} : {{ form.password }}
- {{ form.submit.label }} {{ form.submit }}
- </form>
复制代码 后台定义MyFlaskForm(FlaskForm)类用于对登录表单进行动态渲染。- from flask import Flask, render_template, request,flash
- from flask_wtf import FlaskForm
- from wtforms import StringField, PasswordField, SubmitField
- from wtforms.validators import DataRequired, EqualTo,Length,Regexp
- app = Flask(__name__)
- app.config["SECRET_KEY"] = "d3d3Lmx5c2hhcmsuY29t"
- # 定义表单模型类
- class MyFlaskForm(FlaskForm):
- username = StringField(
- # 标签
- label="账号",
- # 验证器
- validators=[
- DataRequired('请输入用户名')
- ],
- description="账号",
- # 增加附加参数
- render_kw={
- "class":"form-control",
- "placeholder":"请输入用户名",
- "required":'required'
- }
- )
- password = PasswordField(
- label="密码",
- validators=[
- DataRequired('请输入登录密码')
- ],
- description="密码",
- render_kw={
- "class": "form-control",
- "placeholder": "请输入登录密码",
- "required": 'required'
- }
- )
- submit = SubmitField(
- label="登录",
- render_kw={
- "class": "btn",
- }
- )
- @app.route("/", methods=["GET", "POST"])
- def index():
- form = MyFlaskForm()
- if request.method == "POST":
- if form.validate_on_submit():
- username = form.username.data
- password = form.password.data
- print("用户名: {} 密码: {}".format(username, password))
- if username == "lyshark" and password == "123123":
- flash("密码正确")
- else:
- flash("密码错误")
- return render_template("index.html", form=form)
- if __name__ == '__main__':
- app.run(debug=True)
复制代码 运行上述代码,当用户输入密码错误后会出现闪现消息,如下图所示;
地址验证表单
Flask框架中特殊表单的验证有很多,常用的表单验证也就以下这几种。- <form method="post">
- {{ form.csrf_token }}
- <p>{{ form.url.label }} : {{form.url}}</p>
- <p>{{ form.address_v4.label }} : {{form.address_v4}}</p>
- <p>{{ form.address_v6.label }} : {{form.address_v6}}</p>
- <p>{{ form.mac.label }} : {{form.mac}}</p>
- {{form.submit}}
- </form>
复制代码 后台定义MyFlaskForm(FlaskForm)类用于对登录表单进行动态渲染。- from flask import Flask, render_template, request
- from flask_wtf import FlaskForm
- from wtforms import (BooleanField, DecimalField, DateField, DateTimeField, FieldList,
- FloatField, FormField, IntegerField, RadioField, SelectField,
- SelectMultipleField, StringField,SubmitField,PasswordField)
- from wtforms.validators import (DataRequired, data_required, Email, email, EqualTo, equal_to,
- IPAddress, ip_address, InputRequired, input_required, Length,
- length, NumberRange, number_range, Optional, optional,
- Regexp, regexp, URL, url, AnyOf,
- any_of, NoneOf, none_of, MacAddress, mac_address, UUID)
- app = Flask(__name__)
- app.config["SECRET_KEY"] = "d3d3Lmx5c2hhcmsuY29t"
- # 定义表单模型类
- class MyFlaskForm(FlaskForm):
- url = StringField(label=u"验证网址", validators=[DataRequired(), Length(min=6, max=30),URL()])
- address_v4 = StringField(label=u"验证IPv4", validators=[DataRequired(), Length(max=30), IPAddress()])
- address_v6 = StringField(label=u"验证IPv6", validators=[DataRequired(), Length(max=30), IPAddress(ipv6=True)])
- mac = StringField(label=u"验证MAC地址",validators=[DataRequired(), Length(max=60), MacAddress()])
- submit = SubmitField(label=u"提交")
- @app.route("/", methods=["GET", "POST"])
- def index():
- form = MyFlaskForm()
- if request.method == "POST":
- if form.validate_on_submit():
- url = form.url.data
- address_v4 = form.address_v4.data
- address_v6 = form.address_v6.data
- mac = form.mac.data
- print("网址: {} 地址v4: {} 地址v6: {} MAC地址: {}".format(url,address_v4,address_v6,mac))
- return render_template("index.html", form=form)
- return render_template("index.html", form=form)
- if __name__ == '__main__':
- app.run(debug=True)
复制代码 网络IP地址的验证也有相应的表单,如下表单分别可以实现对不同地址的验证;
特殊表单验证
WTF表单除去常规表单验证以外,还可以验证其他特殊表单,例如验证邮箱,浮点数,日期时间等。- <form method="post">
- {{ form.csrf_token }}
-
- <p>{{ form.email.label }} --> {{ form.email }}</p>
- {% for msg in form.email.errors %}
- <p>错误提示: {{msg}}</p>
- {% endfor %}
-
- <p>{{ form.age.label }} --> {{ form.age }}</p>
- {% for msg in form.age.errors %}
- <p>错误提示: {{msg}}</p>
- {% endfor %}
-
- <p>{{ form.height.label }} --> {{ form.height }}</p>
- {% for msg in form.height.errors %}
- <p>错误提示: {{msg}}</p>
- {% endfor %}
-
- <p>{{ form.float_.label }} --> {{ form.float_ }}</p>
- {% for msg in form.float_.errors %}
- <p>错误提示: {{msg}}</p>
- {% endfor %}
-
- <p>{{ form.description.label }} --> {{ form.description }}</p>
- {% for msg in form.description.errors %}
- <p>错误提示: {{msg}}</p>
- {% endfor %}
-
- <p>{{ form.local_date.label }} --> {{ form.local_date }}</p>
- {% for msg in form.local_date.errors %}
- <p>错误提示: {{msg}}</p>
- {% endfor %}
-
- <p>{{ form.time_date.label }} --> {{ form.time_date }}</p>
- {% for msg in form.time_date.errors %}
- <p>错误提示: {{msg}}</p>
- {% endfor %}
-
- <p>{{ form.datetime_date.label }} --> {{ form.datetime_date }}</p>
- {% for msg in form.datetime_date.errors %}
- <p>错误提示: {{msg}}</p>
- {% endfor %}
- {{form.submit}}
- </form>
复制代码 后台定义MyFlaskForm(FlaskForm)类用于对登录表单进行动态渲染。- from flask import Flask, render_template, request
- from flask_wtf import FlaskForm
- from wtforms.validators import DataRequired,Regexp,DataRequired, Length, Email, EqualTo, NumberRange
- from wtforms.fields import (StringField, PasswordField, DateField, BooleanField,DateTimeField,TimeField,
- SelectField, SelectMultipleField, TextAreaField,FloatField,HiddenField,
- RadioField, IntegerField, DecimalField, SubmitField,
- IntegerRangeField)
- app = Flask(__name__)
- app.config["SECRET_KEY"] = "d3d3Lmx5c2hhcmsuY29t"
- # 定义表单模型类
- class MyFlaskForm(FlaskForm):
- # 安装 pip install email-validator
- email = StringField(label=u"邮箱地址", validators=[Email(message=u"邮箱格式错误"),Length(max=32)])
- # 整数类型输入,必须输入整型数值,范围在16到70之间
- age = IntegerField(label=u"年龄", validators=[NumberRange(min=16, max=70)])
- # 小数类型输入,必须输入数字数值,显示时保留两位小数
- height = DecimalField(label=u"小数输入", places=2)
- # 浮点数类型输入,必须输入浮点数值
- float_ = FloatField(label=u"浮点数输入")
- # Text Area类型 段落输入框
- description = TextAreaField(label=u"段落输入")
- # 日期类型输入,必须输入是 "年-月-日" 格式的日期
- local_date = DateField(label=u"日期", format='%Y-%m-%d')
- # 时间类型输入,必须输入是 "时:分:秒" 格式
- time_date = TimeField(label=u"时间", format='%H:%M')
- # 日期时间类型,必须输入是 "年-月-日 时:分:秒" 格式
- datetime_date = DateTimeField(label=u"日期时间", format='%Y-%m-%d %H:%M:%S')
- submit = SubmitField(label=u"提交")
- @app.route("/", methods=["GET", "POST"])
- def index():
- form = MyFlaskForm()
- if request.method == "POST":
- if form.validate_on_submit():
- email = form.email.data
- age = form.age.data
- height = form.height.data
- float_ = form.float_.data
- description = form.description.data
- print("邮箱: {} 年龄: {} 小数点: {} 浮点数: {} 段落输入: {}".format(email,age,height,float_,description))
- local_date = form.local_date.data
- time_date = form.time_date.data
- datetime_date = form.datetime_date.data
- print("日期: {} 时间: {} 日期时间: {}".format(local_date,time_date,datetime_date))
- return render_template("index.html", form=form)
- return render_template("index.html", form=form)
- if __name__ == '__main__':
- app.run(debug=True)
复制代码 特殊表单的构建,这里的表单包括了如下图所示的字段可以使用;
复选多选表单
复选框多选框与下拉选择框三种表单的验证方式总结。- <form method="post">
- {{ form.csrf_token }}
-
- <p>{{ form.gender.label }} {{ form.gender }}</p>
- {% for msg in form.gender.errors %}
- <p>错误提示: {{msg}}</p>
- {% endfor %}
-
- <p>{{ form.jobs.label }} {{ form.jobs }}</p>
- {% for msg in form.jobs.errors %}
- <p>错误提示: {{msg}}</p>
- {% endfor %}
-
- <p>{{ form.hobby.label }} {{ form.hobby }}</p>
- {% for msg in form.hobby.errors %}
- <p>错误提示: {{msg}}</p>
- {% endfor %}
-
- <p>{{ form.accept.label }} {{ form.accept }}</p>
- {% for msg in form.accept.errors %}
- <p>错误提示: {{msg}}</p>
- {% endfor %}
-
- <p>{{ form.favor.label }} {{ form.favor }}</p>
- {% for msg in form.favor.errors %}
- <p>错误提示: {{msg}}</p>
- {% endfor %}
- {{form.submit}}
- </form>
复制代码 后台定义MyFlaskForm(FlaskForm)类用于对登录表单进行动态渲染。- from flask import Flask, render_template, request
- from flask_wtf import FlaskForm
- from wtforms import Form,widgets,validators
- from wtforms.fields import simple,core
- from wtforms.validators import DataRequired,Regexp,DataRequired, Length, Email, EqualTo, NumberRange
- from wtforms.fields import (StringField, PasswordField, DateField, BooleanField,DateTimeField,TimeField,
- SelectField, SelectMultipleField, TextAreaField,FloatField,HiddenField,
- RadioField, IntegerField, DecimalField, SubmitField,
- IntegerRangeField)
- from wtforms.fields import simple,core
- app = Flask(__name__)
- app.config["SECRET_KEY"] = "d3d3Lmx5c2hhcmsuY29t"
- # 定义表单模型类
- class MyFlaskForm(FlaskForm):
- # RadioBox单选框,choices里的内容会在ul标签里,里面每个项是(值,显示名)对
- gender = RadioField(label=u"性别", choices=[('man', '男'), ('wo', '女')], validators=[DataRequired()])
- # Select下拉单选框,choices里的内容会在Option里,里面每个项是(值,显示名)对
- jobs = SelectField(label=u"工作", choices=[("teacher","老师"),("doctor","医生"),("engineer","工程师")])
- # Select多选框,choices里的内容会在Option里,里面每个项是(值,显示名)对
- hobby = SelectMultipleField(label=u"兴趣", choices=[('swim', '渗透'),('skate', '运维'),('hike', '科学')])
- # Checkbox单选框 加上default='checked' 即默认是选上的
- accept = BooleanField(label=u"单选框", default='checked', validators=[DataRequired()])
- # Select复选框, 多选框合并选择,复选框
- favor = SelectMultipleField(
- label="特长",
- choices=((1, 'Python'), (2, '渗透'), (3, "运维"), (4, "科学")),
- coerce=int, default=[1, 2, 4],
- option_widget=widgets.CheckboxInput(),
- widget=widgets.ListWidget(prefix_label=False)
- )
- submit = SubmitField(label=u"提交")
- @app.route("/", methods=["GET", "POST"])
- def index():
- form = MyFlaskForm()
- if request.method == "POST":
- if form.validate_on_submit():
- gender = form.gender.data
- jobs = form.jobs.data
- hobby = form.hobby.data
- accept = form.accept.data
- favor = form.favor.data
- print("性别: {} 工作: {} 兴趣: {} 是否接受: {} 复选框: {}".format(gender,jobs,hobby,accept,favor))
- return render_template("index.html", form=form)
- return render_template("index.html", form=form)
- if __name__ == '__main__':
- app.run(debug=True)
复制代码 选择菜单包括了单选与多选,如下图所示的表单均可以构建;
文件上传表单
文件上传Flask也提供了默认表单可以使用,如下提供的FileField即可完成上传工作。- <form method="POST" action="" enctype="multipart/form-data">
- {{ form.hidden_tag() }}
- {{ form.attach.label }} {{ form.attach }}
- <input type="submit" value="Submit">
- </form>
复制代码 后台定义MyFlaskForm(FlaskForm)类用于对登录表单进行动态渲染。- from flask import Flask, render_template, request
- from flask_wtf import FlaskForm
- from werkzeug.utils import secure_filename
- from flask_wtf.file import FileField, FileAllowed, FileRequired
- app = Flask(__name__)
- app.config["SECRET_KEY"] = "d3d3Lmx5c2hhcmsuY29t"
- # 定义表单模型类
- class MyFlaskForm(FlaskForm):
- attach = FileField(label="上传文件",validators=[
- FileRequired(),
- FileAllowed(["jpg","png"],"只可上传图片")
- ])
- @app.route("/", methods=["GET", "POST"])
- def index():
- form = MyFlaskForm()
- if request.method == "POST":
- if form.validate_on_submit():
- filename = secure_filename(form.attach.data.filename)
- form.attach.data.save('/' + filename)
- return 'Upload successfully!'
- return render_template("index.html", form=form)
- return render_template("index.html", form=form)
- if __name__ == '__main__':
- app.run(debug=True)
复制代码 上传表单时需要注意,启动的进程必须具备管理员权限或者是读写权限,否则则会提示权限拒绝;
来源:https://www.cnblogs.com/LyShark/p/17857906.html
免责声明:由于采集信息均来自互联网,如果侵犯了您的权益,请联系我们【E-Mail:cb@itdo.tech】 我们会及时删除侵权内容,谢谢合作! |
本帖子中包含更多资源
您需要 登录 才可以下载或查看,没有账号?立即注册
x
|