基于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设置路由

  

原文地址:https://www.cnblogs.com/baby123/p/14029739.html