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)
复制代码

关键代码

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

运行

1
python whole 2 .py

另一个窗口执行

1
2
3
4
5
6
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了

1
2
3
4
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)
复制代码

执行

1
python whole 3 .py

另一窗口执行

1
2
3
4
5
6
7
8
jihite@ubuntu:~/project/flask$ curl  127.0 . 0.1: 5000 /todos -d task=hello -d task=hello 2  -d task=hello 4  -X POST
{
     "task" : [
         "hello" ,
         "hello2" ,
         "hello4"
     ]
}

浏览器打开结果

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
{
     "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’ 前面)

  

  





本文转自jihite博客园博客,原文链接:http://www.cnblogs.com/kaituorensheng/p/4661033.html,如需转载请自行联系原作者

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值