**请求参数解析验证数据方法Resource, reqparse**
1、导入模块 from flask_restful import Resource, reqparse
2、创建类
parser = reqparse.RequestParser()
创建时类首先要继承自RequestParse父类
3、使用add_argument()方法添加验证内容
例如:
# 添加评论:book_id、content、Authorization
parser = reqparse.RequestParser()
parser.add_argument('Authorization', type=str, location='headers', required=True, help="当前资源必须提供身份令牌")
parser.add_argument('book_id', type=int, location='json', required=True, help="评论的小说的ID必须提供")
parser.add_argument('content', type=str, location='json', required=True, help="评论的小说的内容必须提供")
4、验证请求数据
# 验证请求数据
args = parser.parse_args() # 如果验证失败时,直接中断请求abort(400) , 如果验证成功,则返回参数的字典
add_argument方法中的参数有:
- name
- default :默认参数,默认为None
- dest :要添加到对象中的属性的名称,默认为None
- required, 默认为False
- ignore: 是否忽略参数类型失败的情况, 默认为False
- type: 参数的类型,错误异常将会在响应中返回, 默认为text_type
- location 请求的对象,要从(例如: location : args, form, json, headers, cookies等)中获取参数,可以是an迭代器,默认为(‘json’, ‘values’,)
- choices: 参数允许值得容器
- help: 参数描述,当参数无效时响应
- action:当此争论时所采取的基本行动类型,默认为store
- trim:如果启用,修改参数周围的空格,默认为False
- nullable:如果启用,参数允许空值,默认为True
- case_sensitive:是否区分大小写,默认为True