flask修改flask_wtf使其支持json数据的validation验证
flask默认是前后端不分离策略,前端通过flask+wtf表单来传递post,put...等数据.
现在前后端分离是趋势,那么对flask进行一定的修改,变为前后端分离,在前端页面中请求后端,那么请求的格式那么必然会有使用json传递数据,然而flask_wtf默认只支持form表单,那么对改动支持json
代码如下:
# coding=utf-8 from flask import request from wtforms import Form from OnlineClassroom.app.err.JsonValidateErr import JsonValidateErr # request data 基础验证器 class RequestBaseForm(Form): # 解析请求参数 def __init__(self): # todo 做个处理,如果请求进来的请求时form参数则else,如果是json则进行下列操作 if "application/json" in request.headers.get("Content-Type"): data = request.get_json(silent=True) args = request.args.to_dict() super(RequestBaseForm, self).__init__(data=data, **args) else: # application/x-www-form-urlencoded or multipart/form-data data = request.form.to_dict() args = request.args.to_dict() super(RequestBaseForm, self).__init__(data=data, **args) # 对验证错误的参数抛出异常 def validate_for_api(self): valid = super(RequestBaseForm, self).validate() if not valid: # todo 这里做一个返回,code,msg,data 错误返回 ??? raise JsonValidateErr("field is require?") return self
根据请求header中content-type来对数据解析,调用wtfforms的Form父类方法__init__将解析过后的参数给予父类的属性,其中自定义方法validate_for_api调用父类的验证方法validate()由父类来确定是否存在与准确
form表单模型:
# coding=utf-8 from .JsonBaseValidate import RequestBaseForm from wtforms import StringField,Form from wtforms.validators import DataRequired,Length class Testform(RequestBaseForm): username = StringField("username",validators=[DataRequired(),Length(min=2,max=20)])
一个简单的测试,路由代码如下:
@user.route("/index",methods=["GET","POST"]) def xx(): req = Testform() type = request.headers.get("Content-Type") if req.validate_for_api(): return "requset username.data {} >> request context-type {}".format(req.username.data,type) return "request validate failds..."
这是json请求,不要忘记在header中将content-type的选项改为applocation/json
这是form-data和form-urlencoded