Flask中使用Flask-WTF验证JSON对象参数
1 安装
Flask-WTF是对WTForms库的扩展,默认只对”form“标签下的表单进行验证。针对当前前后端分离的项目中,json传输参数需要进行二次封装才能使用。
# 安装Flask-WTF包
pip install Flask-WTF
2 源代码
2.1 工程布局
2.2 实体类
request_form.py
# coding=utf-8
from flask import request
from wtforms import Form
# 自定义请求
class RequestForm(Form):
# 初始化参数
def __init__(self):
# 获取 “application/json” 请求
if "application/json" in request.headers.get("Content-Type"):
data = request.get_json(silent=True)
args = request.args.to_dict()
super(RequestForm, self).__init__(data=data, **args)
else:
# 获取 “application/x-www-form-urlencoded” 或者 “multipart/form-data” 请求
data = request.form.to_dict()
args = request.args.to_dict()
super(RequestForm, self).__init__(data=data, **args)
def validate_arguments(self):
# 验证参数
valid = super(RequestForm, self).validate()
# 验证参数失败
if not valid:
# 此处可以写错误返回值
print("field is require")
return self.validate()
test.py
from wtforms import StringField
from wtforms.validators import DataRequired, length
from entity.request_form import RequestForm
# TestForm表单
class TestForm(RequestForm):
# 会自动生成标签
# <input id="name" required type="text" value="参数值">
name = StringField(validators=[DataRequired()])
# 会自动生成标签
# <input id="pwd" maxlength="12" minlength="6" name="pwd" required type="text" value="参数值">
pwd = StringField(validators=[DataRequired(), length(min=6,max=12)])
def get_name_data(self):
return self.name.data
def get_pwd_data(self):
return self.pwd.data
2.3 main.py
flask应用
from flask import Flask
from entity.test import TestForm
app = Flask(__name__)
@app.route("/", methods=['POST'])
def test():
# 获取Form表单
test_form = TestForm()
if not test_form.validate_arguments():
return "The arguments is error"
print(test_form.get_name_data())
print(test_form.get_pwd_data())
return "Success"
if __name__ == '__main__':
app.run(host='0.0.0.0', debug=True)