flask_restful 的reqparse获取验证前端参数

required是设置必选非必选,nullable允不允许向传null,location指定参数获取的位置,可以多选,按前后顺序获取

parser.add_argument('app_id', type=zero_int, required=True, nullable=False, location=['json'])
parser.add_argument('user_num', type=empty_str, required=True, nullable=False, location=['json'])

type基本类型可以有:int , zero_int ,str,empty_str, location可以为:form , json等,详情可查看官方文档。这里要特别说一下如何获取前端的list参数,通过action和type结合使用设置,见下面代码:

parser.add_argument('attachment', action='append', type=str, required=True, nullable=False, location=['json'])

另外,还可以通过  choices= ['day','month']来设置参数可选值,default='xx'来设置默认值

需要注意的是,还支持自定义参数类型校验,如下例子,自定义一个list类型校验:

 

def list_type(value, name):
    if not value:
        return []
    elif not isinstance(value, list):
        raise ValueError(name + '参数类型错误,必须是list类型')
    return value

 

test.add_argument('rd_center_list', type=list_type, required=False, nullable=False, location=['json'])
原文地址:https://www.cnblogs.com/cherylgi/p/13071586.html