基于Flask的 api(三)
使用flask的RESTful扩展库 flask-restful
安装
pip install flask-restful
eg:
最简单的api
from flask import Flask from flask_restful import Api, Resource 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,port=5000)
测试
$ curl -i http://localhost:5000 % Total % Received % Xferd Average Speed Time Time Time Current Dload Upload Total Spent Left Speed 100 25 100 25 0 0 25 0 0:00:01 --:--:-- 0:00:01 123HTTP/1.0 200 OK Content-Type: application/json Content-Length: 25 Server: Werkzeug/1.0.1 Python/3.7.7 Date: Tue, 24 Nov 2020 04:31:12 GMT { "hello": "world" }
restful api
from flask import Flask from flask_restful import reqparse, abort, Api, Resource app = Flask(__name__) api = Api(app) tasks = [ { 'id': 1, 'title': u'Buy groceries', 'description': u'Milk, Cheese, Pizza, Fruit, Tylenol', 'done': False }, { 'id': 2, 'title': u'Learn Python', 'description': u'Need to find a good Python tutorial on the web', 'done': False } ] def abort_if_todo_doesnt_exist(task,id): if len(task) ==0: abort(404, message="task {} doesn't exist".format(id)) parser = reqparse.RequestParser() parser.add_argument('title') parser.add_argument('description') parser.add_argument('done') # (put/get/delete)Task class Task(Resource): def get(self, id): task = list(filter(lambda t: t['id']==id,tasks)) abort_if_todo_doesnt_exist(task,id) return task def delete(self, id): task = list(filter(lambda t: t['id']==id,tasks)) abort_if_todo_doesnt_exist(task,id) tasks.remove(task[0]) return {'result': True,'list':tasks} def put(self, id): task = list(filter(lambda t: t['id']==id,tasks)) abort_if_todo_doesnt_exist(task,id) args = parser.parse_args() task[0]['title'] = args['title'] task[0]['description'] = args['description'] task[0]['done'] = args['done'] return task, 201 #(post/get)TaskList class TaskList(Resource): def get(self): return tasks def post(self): args = parser.parse_args() task = { 'id': tasks[-1]['id'] + 1, 'title': args['title'], 'description': args['description'], 'done': False } tasks.append(task) return task, 201 # 设置路由 api.add_resource(TaskList, '/tasks') api.add_resource(Task, '/tasks/<int:id>') if __name__ == "__main__": app.run(debug=True,port=5000)
说明:
RequestParser参数解析类,可以很方便的解析请求中的-d参数,并进行类型转换
使用add_resource设置路由
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 【杭电多校比赛记录】2025“钉耙编程”中国大学生算法设计春季联赛(1)