一、Flask_RESTful——请求解析
Flask-RESTful 的请求解析接口是模仿 argparse 接口。
它设计成提供简单并且统一的访问 Flask 中 flask.request 对象里的任何变量的入口。
from flask.ext.restful import reqparse
# 创建参数解析对象,进行请求参数解析
parser = reqparse.RequestParser()
# 请求携带参数格式
parser.add_argument('rate', type=int, help='Rate cannot be converted')
parser.add_argument('name', type=str)
# 参数解析完成,获取参数解析数据。
args = parser.parse_args() # 返回结果是一个字典
1、add_argument中选项详解
必须的参数
1、要求一个值传递的参数,只需要添加 required=True 来调用 add_argument()。
parser.add_argument('name', type=str, required=True,help="Name cannot be blank!")
多个值&列表
1、如果你要接受一个键有多个值的话,你可以传入 action=‘append’
parser.add_argument('name', type=str, action='append')
解析替换目标
1、你想要以不同的名称存储你的参数一旦它被解析的时候,你可以使用 dest kwarg。
parser.add_argument('name', type=str, dest='public_name')
args = parser.parse_args()
args['public_name']
指定参数解析的位置
1、默认下,RequestParser 试着从 flask.Request.values,以及 flask.Request.json 解析值。
2、在 add_argument() 中使用 location 参数可以指定解析参数的位置。flask.Request 中任何变量都能被使用。
# Look only in the POST body
parser.add_argument('name', type=int, location='form')
# Look only in the querystring
parser.add_argument('PageSize', type=int, location='args')
# From the request headers
parser.add_argument('User-Agent', type=str, location='headers')
# From http cookies
parser.add_argument('session_id', type=str, location='cookies')
# From file uploads
parser.add_argument('picture', type=werkzeug.datastructures.FileStorage, location='files')
指定多个参数解析的位置
1、通过传入一个列表到 location 中可以指定 多个 参数位置:
parser.add_argument('text', location=['headers', 'values'])
继承解析
1、编写一个包含所有共享参数的父解析器接着使用 copy() 扩充它。
2、你也可以使用 replace_argument() 覆盖父级的任何参数。
3、或者使用 remove_argument() 完全删除参数。
from flask.ext.restful import RequestParser
parser = RequestParser()
parser.add_argument('foo', type=int)
parser_copy = parser.copy()
parser_copy.add_argument('bar', type=int)
# parser_copy has both 'foo' and 'bar'
parser_copy.replace_argument('foo', type=str, required=True, location='json')
# 'foo' is now a required str located in json, not an int as defined
# by original parser
parser_copy.remove_argument('foo')
# parser_copy no longer has 'foo' argument