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