基於Flask的 api(三)
阿新 • • 發佈:2020-11-24
使用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.0200 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設定路由