11.22 Flask-RESTful 请求解析

Flask-RESTful 请求解析

一、基本参数

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()

二、必需的参数

parser.add_argument('name', type=str, required=True,help="Name cannot be blank!")

三、多个值&列表

parser.add_argument('name', type=str, action='append')

1. 请求:

curl http://api.example.com -d "Name=bob" -d "Name=sue" -d "Name=joe"

2. 接收:

args = parser.parse_args()args['name'] # ['bob', 'sue', 'joe']

四、Destinations

parser.add_argument('name', type=str, dest='public_name')

args = parser.parse_args()args['public_name']

五、参数位置

# 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')

六、多个位置

  • 例如:location=['headers', 'values'],解析后'values'的结果会在'headers'前面
parser.add_argument('text', location=['headers', 'values'])

七、继承解析

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

摘录自Flask-RESTful文档<>篇


分享到:


相關文章: