flask-restful 请求解析

基本参数

from flask import Flask
from flask.ext.restful import reqparse, abort, Api, Resource

app = Flask(__name__)
api = Api(app)

TODOS = { 'todo1': {'task': 'build an API'},
    'todo2': {'task': '?????'},
    'todo3': {'task': 'profit!'},
}


parser = reqparse.RequestParser()
parser.add_argument('task', type=str, help='Rate cannot be converted')
parser.add_argument('rate', type=int)

def abort_if_todo_doesnt_exist(todo_id):
    if todo_id not in TODOS:
        abort(404, message="Todo {} doesn't exist".format(todo_id))

# TodoList
#   shows a list of all todos, and lets you POST to add new tasks
class TodoList(Resource):
    def get(self):
        return TODOS

    def post(self):
        args = parser.parse_args()
        todo_id = int(max(TODOS.keys()).lstrip('todo')) + 1
        todo_id = 'todo%i' % todo_id
        TODOS[todo_id] = {'task': args['task']}
        return TODOS[todo_id], 201

##
## Actually setup the Api resource routing here
##
api.add_resource(TodoList, '/todos')

if __name__ == '__main__':
    app.run(debug=True)

关键代码

parser = reqparse.RequestParser()
parser.add_argument('task', type=str, help='Rate cannot be converted')
parser.add_argument('rate', type=int)

args = parser.parse_args()

指定了help信息,在解析类型错误的时候,就会作为错误信息呈现出来;否则默认返回类型错误本身的错误。

必须的参数

添加条件

whole2.py

from flask import Flask
from flask.ext.restful import reqparse, abort, Api, Resource

app = Flask(__name__)
api = Api(app)

TODOS = { 'todo1': {'task': 'build an API'},
    'todo2': {'task': '?????'},
    'todo3': {'task': 'profit!'},
}


parser = reqparse.RequestParser()
parser.add_argument('task', type=str, help='Rate cannot be converted')
parser.add_argument('rate', type=int, required=Ture)

def abort_if_todo_doesnt_exist(todo_id):
    if todo_id not in TODOS:
        abort(404, message="Todo {} doesn't exist".format(todo_id))

# TodoList
#   shows a list of all todos, and lets you POST to add new tasks
class TodoList(Resource):
    def get(self):
        return TODOS

    def post(self):
        args = parser.parse_args()
        todo_id = int(max(TODOS.keys()).lstrip('todo')) + 1
        todo_id = 'todo%i' % todo_id
        TODOS[todo_id] = {'task': args['task']}
        return TODOS[todo_id], 201

##
## Actually setup the Api resource routing here
##
api.add_resource(TodoList, '/todos')

if __name__ == '__main__':
    app.run(debug=True)

关键代码

parser.add_argument('rate', type=int, required=Ture)

运行

python whole2.py

另一个窗口执行

jihite@ubuntu:~/project/flask$ curl 127.0.0.1:5000/todos -d task=hello -X POST
{
    "message": {
        "rate": "Missing required parameter in the JSON body or the post body or the query string"
    }
}

添加rate参数再执行,就ok了

jihite@ubuntu:~/project/flask$ curl 127.0.0.1:5000/todos -d task=hello -d rate=3 -X POST
{
    "task": "hello"
}

多个值&列表

whole3.py

from flask import Flask
from flask.ext.restful import reqparse, abort, Api, Resource

app = Flask(__name__)
api = Api(app)

TODOS = { 'todo1': {'task': 'build an API'},
    'todo2': {'task': '?????'},
    'todo3': {'task': 'profit!'},
}


parser = reqparse.RequestParser()
parser.add_argument('task', type=str, action='append')

def abort_if_todo_doesnt_exist(todo_id):
    if todo_id not in TODOS:
        abort(404, message="Todo {} doesn't exist".format(todo_id))

# TodoList
#   shows a list of all todos, and lets you POST to add new tasks
class TodoList(Resource):
    def get(self):
        return TODOS

    def post(self):
        args = parser.parse_args()
        todo_id = int(max(TODOS.keys()).lstrip('todo')) + 1
        todo_id = 'todo%i' % todo_id
        TODOS[todo_id] = {'task': args['task']}
        return TODOS[todo_id], 201

##
## Actually setup the Api resource routing here
##
api.add_resource(TodoList, '/todos')

if __name__ == '__main__':
    app.run(debug=True)

执行

python whole3.py

另一窗口执行

jihite@ubuntu:~/project/flask$ curl 127.0.0.1:5000/todos -d task=hello -d task=hello2 -d task=hello4 -X POST
{
    "task": [
        "hello", 
        "hello2", 
        "hello4"
    ]
}

浏览器打开结果

{
    "todo1": {
        "task": "build an API"
    }, 
    "todo2": {
        "task": "?????"
    }, 
    "todo3": {
        "task": "profit!"
    }, 
    "todo4": {
        "task": [
            "hello", 
            "hello2", 
            "hello4"
        ]
    }
}

参数位置

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

多个位置

parser.add_argument('text', location=['headers', 'values'])

列表中最后一个优先出现在结果集中。(例如:location=[‘headers’, ‘values’],解析后 ‘values’ 的结果会在 ‘headers’ 前面)

  

  

posted @ 2015-07-20 11:55  jihite  阅读(11479)  评论(0编辑  收藏  举报