一、基本參數
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文檔<>篇
閱讀更多 編程小鑫 的文章