flask 插件 Flask-RESTful

2023-09-15 10:47:22

1、安装

pip install flask-restful

2、使用

Hello World

一个简单的例子:

# -*- coding: utf-8 -*-
from flask import Flask
from flask_restful import Resource, Api
app = Flask(__name__)
api = Api(app)
class HelloWorld(Resource):
    def get(self):
        return {'hello': 'world'}
api.add_resource(HelloWorld, '/')
if __name__ == '__main__':
    app.run(debug=True)

上面的代码应该不难看懂。我们定义了一个 HelloWorld 的类,该类继承自 Resource,在类里面,我们定义了 get 方法,该方法跟 HTTP 请求中的 GET 方法对应。接着,我们使用 add_resource() 方法添加资源,该方法的第 1 个参数就是我们定义的类,第 2 个参数是 URL 路由。

将上面的代码保存为 app.py,在终端运行:

$ python app.py
 * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
 * Restarting with stat
 * Debugger is active!
 * Debugger pin code: 109-566-036

使用 curl 测试,如下:

$ curl http://127.0.0.1:5000/
{
    "hello": "world"
}

另外,add_resource() 方法也支持添加多个路由,比如:

api.add_resource(HelloWorld, '/', '/hello')

这样访问 http://127.0.0.1:5000/ 和 http://127.0.0.1:5000/hello 效果是一样的。

带参数的请求

Flask-RESTful 也支持路由带参数的请求,跟 Flask 的实现是类似的,看下面这个例子。

# -*- coding: utf-8 -*-
from flask import Flask, request
from flask_restful import Resource, Api
app = Flask(__name__)
api = Api(app)
todos = {}
class TodoSimple(Resource):
    def get(self, todo_id):
        return {todo_id: todos[todo_id]}
    def put(self, todo_id):
        todos[todo_id] = request.form['data']
        return {todo_id: todos[todo_id]}
# 路由带参数
api.add_resource(TodoSimple, '/<string:todo_id>')
if __name__ == '__main__':
    app.run(debug=True)

使用 curl 测试,如下:

$ curl -X PUT http://localhost:5000/todo1 -d "data=shopping"
{
    "todo1": "shopping"
}
$ curl -X GET http://localhost:5000/todo1
{
    "todo1": "shopping"
}

参数解析
Flask-RESTful 提供了 reqparse 库来简化我们访问并验证表单的工作,将上面的代码使用 reqparse 改写,如下:

# -*- coding: utf-8 -*-
from flask import Flask, request
from flask_restful import Resource, Api, reqparse
app = Flask(__name__)
api = Api(app)
parser = reqparse.RequestParser()
parser.add_argument('task', type=str)  # 相当于添加 form 表单字段,并给出类型
todos = {}
class TodoSimple(Resource):
    def get(self, todo_id):
        return {todo_id: todos[todo_id]}
    def put(self, todo_id):
        args = parser.parse_args()   # 获取表单的内容, args 是一个字典
        if args['task']:
            todos[todo_id] = args['task']   
        else:
            return 'error!'
        return {todo_id: todos[todo_id]}
api.add_resource(TodoSimple, '/<string:todo_id>')
if __name__ == '__main__':
    app.run(debug=True)

上面的代码中,我们使用 add_argument() 方法添加 form 表单字段,并指定其类型。获取表单内容使用 parse_args() 方法,该方法返回一个字典,字典的 key 就是表单的字段。

使用 curl 测试,如下:

$ curl -X PUT http://localhost:5000/todo1 -d "task=shopping"
{
    "todo1": "shopping"
}

一个完整的例子

下面这个完整的例子来自于官方文档。

from flask import Flask
from flask_restful import reqparse, abort, Api, Resource
app = Flask(__name__)
api = Api(app)
TODOS = {
    'todo1': {'task': 'build an API'},
    'todo2': {'task': '?????'},
    'todo3': {'task': 'profit!'},
}
def abort_if_todo_doesnt_exist(todo_id):
    if todo_id not in TODOS:
        abort(404, message="Todo {} doesn't exist".format(todo_id))
parser = reqparse.RequestParser()
parser.add_argument('task')
# Todo
# shows a single todo item and lets you delete a todo item
class Todo(Resource):
    def get(self, todo_id):
        abort_if_todo_doesnt_exist(todo_id)
        return TODOS[todo_id]
    def delete(self, todo_id):
        abort_if_todo_doesnt_exist(todo_id)
        del TODOS[todo_id]
        return '', 204
    def put(self, todo_id):
        args = parser.parse_args()
        task = {'task': args['task']}
        TODOS[todo_id] = task
        return task, 201
# 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')
api.add_resource(Todo, '/todos/<todo_id>')
if __name__ == '__main__':
    app.run(debug=True)

运行上面的代码,然后使用 curl 进行测试,如下:

# 获取所有 todos
$ curl http://localhost:5000/todos
{
    "todo1": {
        "task": "build an API"
    },
    "todo2": {
        "task": "?????"
    },
    "todo3": {
        "task": "profit!"
    }
}
# 获取单个 todo
$ curl http://localhost:5000/todos/todo2
{
    "task": "?????"
}
# 删除某个 todo
$ curl -v -X DELETE http://localhost:5000/todos/todo2
*   Trying 127.0.0.1...
* Connected to localhost (127.0.0.1) port 5000 (#0)
> DELETE /todos/todo2 HTTP/1.1
> Host: localhost:5000
> User-Agent: curl/7.43.0
> Accept: */*
>
* HTTP 1.0, assume close after body
< HTTP/1.0 204 NO CONTENT
< Content-Type: application/json
< Content-Length: 0
< Server: Werkzeug/0.11.11 Python/2.7.11
< Date: Tue, 18 Oct 2016 04:02:17 GMT
<
* Closing connection 0
# 添加 todo
$ curl -v -X POST http://localhost:5000/todos -d "task=eating"
*   Trying 127.0.0.1...
* Connected to localhost (127.0.0.1) port 5000 (#0)
> POST /todos HTTP/1.1
> Host: localhost:5000
> User-Agent: curl/7.43.0
> Accept: */*
> Content-Length: 11
> Content-Type: application/x-www-form-urlencoded
>
* upload completely sent off: 11 out of 11 bytes
* HTTP 1.0, assume close after body
< HTTP/1.0 201 CREATED
< Content-Type: application/json
< Content-Length: 25
< Server: Werkzeug/0.11.11 Python/2.7.11
< Date: Tue, 18 Oct 2016 04:04:16 GMT
<
{
    "task": "eating"
}
* Closing connection 0
# 更新 todo
$ curl -v -X PUT http://localhost:5000/todos/todo3 -d "task=running"
*   Trying 127.0.0.1...
* Connected to localhost (127.0.0.1) port 5000 (#0)
> PUT /todos/todo3 HTTP/1.1
> Host: localhost:5000
> User-Agent: curl/7.43.0
> Accept: */*
> Content-Length: 12
> Content-Type: application/x-www-form-urlencoded
>
* upload completely sent off: 12 out of 12 bytes
* HTTP 1.0, assume close after body
< HTTP/1.0 201 CREATED
< Content-Type: application/json
< Content-Length: 26
< Server: Werkzeug/0.11.11 Python/2.7.11
< Date: Tue, 18 Oct 2016 04:05:52 GMT
<
{
    "task": "running"
}
* Closing connection 0
更多推荐

MySQL

数据库分两大类:关系型数据SQL非关系型数据库NoSQL关系型数据库典型代表:MySQLMariaDBPostgreSQL(pgsql)OracleSQLServerDB2国产数据库:阿里云RDB华为高斯阿里Oceanbase腾讯TDBA1.SQLSQL(StructuredQueryLanguage)是具有数据操纵和

Spring-动态代理深入了解

😀前言本篇的Spring-AOP系类文章第二篇扩展了Spring-动态代理然后开发了简易的AOP类🏠个人主页:尘觉主页🧑个人简介:大家好,我是尘觉,希望我的文章可以帮助到大家,您的满意是我的动力😉😉在csdn获奖荣誉:🏆csdn城市之星2名⁣⁣⁣⁣⁣⁣⁣⁣⁣⁣⁣⁣⁣⁣⁣⁣⁣⁣⁣⁣⁣⁣⁣⁣⁣⁣⁣⁣⁣⁣⁣⁣💓

Nginx服务优化措施、网页安全与配置防盗链

目录一.优化Nginx二.隐藏/查看版本号隐藏版本号方法一:修改配置文件,关闭版本号隐藏版本号方法二:修改源码文件中的版本号,重新编译安装三.修改用户与组四.设置缓存时间五.日志切割脚本六.设置连接超时控制连接访问时间七.开启多进程八.配置网页压缩九.配置防盗链9.1.配置web源主机(192.168.47.103)9

【Python】PySpark 数据计算 ① ( RDD#map 方法 | RDD#map 语法 | 传入普通函数 | 传入 lambda 匿名函数 | 链式调用 )

文章目录一、RDD#map方法1、RDD#map方法引入2、RDD#map语法3、RDD#map用法4、代码示例-RDD#map数值计算(传入普通函数)5、代码示例-RDD#map数值计算(传入lambda匿名函数)6、代码示例-RDD#map数值计算(链式调用)一、RDD#map方法1、RDD#map方法引入在PyS

API网关是如何提升API接口安全管控能力的

API安全的重要性近几年,越来越多的企业开始数字化转型之路。数字化转型的核心是将企业的服务、资产和能力打包成服务(服务的形式通常为API,API又称接口,下文中提到的API和接口意思相同),从而让资源之间形成更强的连接和互动关系,释放原有资产的价值,提升企业的服务能力。企业数字化转型使得基于API的业务系统剧增,随之而

RK3568笔记分享之“如何挂载SPI FRAM铁电存储芯片”——飞凌嵌入式

对于做快速存储采集数据类产品的用户来说,在处理突发掉电情况时需要保存现有数据并避免数据丢失,这种情况下有很多种解决方案,铁电存储器(FRAM)就是个很好的选择。FRAM是一种具有快速写入速度的非易失性存储器,既可以进行非易失性数据存储,又可以像RAM一样操作。本文将借助飞凌嵌入式OK3568-C开发板来为大家介绍一种采

周界警戒AI算法+视频智能分析在安全生产场景中的应用

长期以来,周界防范安防系统在大型园区、工厂、社区、机场、火车站站台、重点单位等领域应用较为广泛和常见。随着AI人工智能等新兴技术的快速发展与落地应用,通过AI智能检测与视频智能分析技术,现代化的周界安防系统可以做到全天候快速、准确地发现入侵等异常事件,并及时报警遏制。今天我们来介绍下旭帆科技安全生产周界警戒AI算法的具

[2023.09.18]: Rust中类型转换在错误处理中的应用解析

随着项目的进展,关于Rust的故事又翻开了新的一页,今天来到了服务器端的开发场景,发现错误处理中的错误类型转换有必要分享一下。Rust抽象出来了Result<T,E>,T是返回值的类型,E是错误类型。只要函数的返回值的类型被定义为Resut<T,E>,那么作为开发人员就有责任来处理调用这个函数可能发生的错误。通过Res

CIIS 2023丨聚焦文档图像处理前沿领域,合合信息AI助力图像处理与内容安全保障

近日,2023第十二届中国智能产业高峰论坛(CIIS2023)在江西南昌顺利举行。大会由中国人工智能学会、江西省科学技术厅、南昌市人民政府主办,南昌市科学技术局、中国工程科技发展战略江西研究院承办。本次大会重点关注AI大模型、生成式AI、无人系统、智能制造、数字安全等领域,汇集了来自中国工程院、国际欧亚科学院、国际核能

聚观早报|高德发布安全出行大模型;小鹏G9焕新上市

【聚观365】9月21日消息高德发布安全出行大模型小鹏G9焕新上市妙鸭相机上线免费版RedmiNote13Pro+支持IP68Neuralink将进行首次人体临床试验高德发布安全出行大模型高德发布了安全出行大模型。据介绍,安全出行大模型基于高德的地图大数据、位置大数据、导航大数据、智能决策系统等能力,从风险识别、风险预

悬崖边:企业如何应对网络安全漏洞趋势

在本文中,我们将讨论企业在处理漏洞时面临的挑战,解释安全漏洞是如何引发网络攻击的,以及为什么它会导致不可接受的事件。我们还将分享我们在识别趋势性漏洞方面的经验。现代信息安全方法正在成为企业的工作流程。例如,不久前,整个IT行业都在向容器化发展,而对云环境的安全和保护机制的研究还是个新鲜事物。现在,几乎每家公司在产品架构

热文推荐