Flask 之 RESTful


1. the Flask-a RESTful  Overview; 


The main resource base is 1.1 Flask-RESTful provided (resources). Resources (Resources) is built in the  Flask view pluggable  above, (resource) defined on the resource as long as you can easily access method of a plurality of HTTP methods. A resource-do basic CRUD application looks like this: The main resource base is provided (resources). Resources (Resources) is built in the  Flask view pluggable  above, (resource) defined on the resource as long as you can easily access method of a plurality of HTTP methods. A resource-do basic CRUD application looks like this :


1.2 mind map;

image.png


2. The example code;

from flask import Flask, request
from flask_restful import reqparse, abort, Api, Resource

app = Flask(__name__)
api = Api(app)

TODOS = {
    'todo1': {'task': '我是第一个测试'},
    'todo2': {'task': '我是第二个测试'},
    'todo3': {'task': '我是第三个测试'},
}


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', type=str)



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



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

api.add_resource(TodoList, '/todos')
api.add_resource(Todo, '/todos/<todo_id>')


if __name__ == '__main__':
    app.run(debug=True)



(1)引入需要的库名、函数、变量等,并做简单的Application初始化:

from flask import Flaskfrom flask_restful import reqparse, abort, Api, Resource
app = Flask(__name__)
api = Api(app)

(2)定义我们需要操作的资源类型(都是json格式的):

TODOS = {
    'todo1': {'task': '我是第一个测试'},
    'todo2': {'task': '我是第二个测试'},
    'todo3': {'task': '我是第三个测试'},
}

(3)Flask-RESTful提供了一个用于参数解析的RequestParser类,类似于Python中自带的argparse类,可以很方便的解析请求中的-d参数,并进行类型转换。

parser = reqparse.RequestParser()  
parser.add_argument('task')

(4)我们观察标准的API接口,这里的接口可以分为两类:带有item_id的,和不带有item_id的。前者是操作单一资源,后者是操作资源列表或新建一个资源。

从操作单一资源开始,继承Resource类,并添加put / get / delete方法:

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

(5)继续操作资源列表,继承Resource类,并添加get / post方法:

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

(6) After operating resource class defined, you need to set the route that tells Python program correspondence between a URL.

api.add_resource (TodoList, '/ all') 
api.add_resource (Everything '/ all / <todo_id>')


3.Postman testing;










Guess you like

Origin blog.51cto.com/breaklinux/2424189