基于Flask的 api(二)
使用flask 构造服务的方法有:
(1)利用路由实现
(2)利用flask的扩展插件实现
利用路由实现REST API
1.GET
获取资源
获取列表
from flask import Flask,request,abort,jsonify app = Flask(__name__) 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 } ] @app.route("/tasks", methods=['GET']) def get_tasks(): return jsonify({'tasks': tasks}) if __name__ == "__main__": app.run(debug=True)
测试
$ curl -i http://localhost:5000/tasks % Total % Received % Xferd Average Speed Time Time Time Current Dload Upload Total Spent Left Speed 100 218 100 218 0 0 931 0 --:--:-- --:--:-- --:--:-- 931HTTP/1.0 200 OK Content-Type: application/json Content-Length: 218 Server: Werkzeug/1.0.1 Python/3.6.0 Date: Mon, 23 Nov 2020 13:45:24 GMT {"tasks":[{"description":"Milk, Cheese, Pizza, Fruit, Tylenol","done":false,"id":1,"title":"Buy groceries"},{"description":"Need to find a good Python tutorial on the web","done":false,"id":2,"title":"Learn Python"}]}
获取其中一个
from flask import Flask,request,abort,jsonify app = Flask(__name__) 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 } ] @app.route("/tasks/<int:task_id>", methods=['GET']) def get_task(task_id): task = list(filter(lambda t: t['id'] == task_id, tasks)) if len(task) == 0: abort(404) return jsonify({'task': task[0]}) if __name__ == "__main__": app.run(debug=True)
测试
$ curl -i http://localhost:5000/tasks/1 % Total % Received % Xferd Average Speed Time Time Time Current Dload Upload Total Spent Left Speed 100 142 100 142 0 0 606 0 --:--:-- --:--:-- --:--:-- 606HTTP/1.0 200 OK Content-Type: application/json Content-Length: 142 Server: Werkzeug/1.0.1 Python/3.6.0 Date: Mon, 23 Nov 2020 14:31:42 GMT { "task": { "description": "Milk, Cheese, Pizza, Fruit, Tylenol", "done": false, "id": 1, "title": "Buy groceries" } }
2.POST
创建资源
from flask import Flask,request,abort,jsonify app = Flask(__name__) 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 } ] @app.route('/tasks', methods=['POST']) def create_task(): if not request.json or not 'title' in request.json: abort(400) task = { 'id': tasks[-1]['id'] + 1, 'title': request.json['title'], 'description': request.json.get('description', ""), 'done': False } tasks.append(task) return jsonify({'newTask': task,'list':tasks}), 201 if __name__ == "__main__": app.run(debug=True)
测试
$ curl -i -H "Content-Type: application/json" -X POST -d '{"title":"ABC"}' http://localhost:5000/tasks % Total % Received % Xferd Average Speed Time Time Time Current Dload Upload Total Spent Left Speed 100 528 100 513 100 15 2192 64 --:--:-- --:--:-- --:--:-- 2256HTTP/1.0 201 CREATED Content-Type: application/json Content-Length: 513 Server: Werkzeug/1.0.1 Python/3.6.0 Date: Mon, 23 Nov 2020 14:38:50 GMT { "list": [ { "description": "Milk, Cheese, Pizza, Fruit, Tylenol", "done": false, "id": 1, "title": "Buy groceries" }, { "description": "Need to find a good Python tutorial on the web", "done": false, "id": 2, "title": "Learn Python" }, { "description": "", "done": false, "id": 3, "title": "ABC" } ], "newTask": { "description": "", "done": false, "id": 3, "title": "ABC" } }
3.PUT
更新资源
from flask import Flask,request,abort,jsonify app = Flask(__name__) 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 } ] @app.route('/tasks/<int:task_id>', methods=['PUT']) def update_task(task_id): task = list(filter(lambda t:t['id']==task_id,tasks)) if len(task)==0: abort(404) if not request.json: abort(400) if 'title' in request.json and not isinstance(request.json['title'],str): abort(400) if 'description' in request.json and not isinstance(request.json['description'],str): abort(400) if 'done' in request.json and not isinstance(request.json['done'],bool): abort(400) task[0]['title'] = request.json.get('title',task[0]['title']) task[0]['description'] = request.json.get('description', task[0]['description']) task[0]['done'] = request.json.get('done', task[0]['done']) return jsonify({'task':task[0]}) if __name__ == "__main__": app.run(debug=True)
测试
$ curl -i -H "Content-Type: application/json" -X PUT -d '{"title":"ABC"}' http://localhost:5000/tasks/1 % Total % Received % Xferd Average Speed Time Time Time Current Dload Upload Total Spent Left Speed 100 147 100 132 100 15 564 64 --:--:-- --:--:-- --:--:-- 628HTTP/1.0 200 OK Content-Type: application/json Content-Length: 132 Server: Werkzeug/1.0.1 Python/3.6.0 Date: Mon, 23 Nov 2020 15:00:31 GMT { "task": { "description": "Milk, Cheese, Pizza, Fruit, Tylenol", "done": false, "id": 1, "title": "ABC" } }
4.DELETE
删除资源
from flask import Flask,request,abort,jsonify app = Flask(__name__) 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 } ] @app.route('/tasks/<int:task_id>',methods=['DELETE']) def delete_task(task_id): task = list(filter(lambda t: t['id']==task_id,tasks)) if len(task) ==0: abort(404) tasks.remove(task[0]) return jsonify({'result': True,'list':tasks}) if __name__ == "__main__": app.run(debug=True)
测试
$ curl -i -H "Content-Type: application/json" -X DELETE http://localhost:5000/tasks/1 % Total % Received % Xferd Average Speed Time Time Time Current Dload Upload Total Spent Left Speed 100 191 100 191 0 0 812 0 --:--:-- --:--:-- --:--:-- 812HTTP/1.0 200 OK Content-Type: application/json Content-Length: 191 Server: Werkzeug/1.0.1 Python/3.6.0 Date: Mon, 23 Nov 2020 15:02:52 GMT { "list": [ { "description": "Need to find a good Python tutorial on the web", "done": false, "id": 2, "title": "Learn Python" } ], "result": true }
【推荐】国内首个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)