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,如需转载请自行联系原作者

相关文章
|
4月前
|
存储 算法 安全
JWT深度解析:现代Web身份验证的通行证为什么现在都是JWT为什么要restful-优雅草卓伊凡
JWT深度解析:现代Web身份验证的通行证为什么现在都是JWT为什么要restful-优雅草卓伊凡
252 41
JWT深度解析:现代Web身份验证的通行证为什么现在都是JWT为什么要restful-优雅草卓伊凡
|
12月前
|
Java 网络架构 Spring
springboot中restful风格请求的使用
本文介绍了在Spring Boot中如何使用RESTful风格的请求,包括创建HTML表单页面、在application.yaml配置文件中开启REST表单支持、编写Controller层及对应映射处理,并进行服务启动和访问测试。HTML表单默认只支持GET和POST请求,因此对于DELETE和PUT请求,需要使用隐藏域`_method`来支持。
springboot中restful风格请求的使用
|
9月前
|
XML JSON JavaScript
HttpGet 请求的响应处理:获取和解析数据
HttpGet 请求的响应处理:获取和解析数据
|
10月前
|
前端开发 Java 开发者
Spring MVC中的请求映射:@RequestMapping注解深度解析
在Spring MVC框架中,`@RequestMapping`注解是实现请求映射的关键,它将HTTP请求映射到相应的处理器方法上。本文将深入探讨`@RequestMapping`注解的工作原理、使用方法以及最佳实践,为开发者提供一份详尽的技术干货。
865 2
|
10月前
|
存储 API 数据库
使用Python和Flask构建简单的RESTful API
使用Python和Flask构建简单的RESTful API
196 2
|
10月前
|
JSON 关系型数据库 测试技术
使用Python和Flask构建RESTful API服务
使用Python和Flask构建RESTful API服务
454 2
|
10月前
|
JSON API 数据格式
如何使用Python和Flask构建一个简单的RESTful API。Flask是一个轻量级的Web框架
本文介绍了如何使用Python和Flask构建一个简单的RESTful API。Flask是一个轻量级的Web框架,适合小型项目和微服务。文章从环境准备、创建基本Flask应用、定义资源和路由、请求和响应处理、错误处理等方面进行了详细说明,并提供了示例代码。通过这些步骤,读者可以快速上手构建自己的RESTful API。
586 2
|
11月前
|
JSON API 数据格式
使用Python和Flask构建简单的RESTful API
【10月更文挑战第12天】使用Python和Flask构建简单的RESTful API
135 1
|
11月前
|
API 数据库 网络架构
深入浅出:使用Python Flask实现RESTful API
【10月更文挑战第7天】在数字化时代,掌握如何高效构建和部署RESTful API是后端开发者的必备技能。本文将引导你了解如何使用Python Flask框架快速打造一个简单而强大的RESTful服务。从基础环境搭建到API设计原则,再到实际代码示例,我们将一步步揭开Flask框架的神秘面纱,让你轻松上手,并能够自信地处理更复杂的项目。
|
12月前
|
JSON Go API
使用Go语言和Gin框架构建RESTful API:GET与POST请求示例
使用Go语言和Gin框架构建RESTful API:GET与POST请求示例

推荐镜像

更多
  • DNS