Flask-RESTful插件介绍--2017年4月7日

Flask-RESTful概述:为了快速构建RESTful API的Flask插件,能和现有的ORM配合的轻量级数据抽象
参考链接:http://www.pythondoc.com/Flask-RESTful/quickstart.html
http://dormousehole.readthedocs.io/en/latest/可插拔视图
资源路由:资源(Resources)是构建在 Flask 可拔插视图 之上,只要在你的资源(resource)上定义方法就能够容易地访问多个 HTTP 方法。
参数解析:Flask-RESTful 内置了支持验证请求数据,它使用了一个类似 argparse 的库。
数据格式化:Flask-RESTful 提供了 fields 模块和 marshal_with() 装饰器。

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

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

todos ={
    'todo1':{'task':'build an API'},
    'todo2':{'task':'????'},
    'todo3':{'task':'profit!'},
}

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
    
class TodoSimple(Resource):
    def get(self,todo_id):
        return {todo_id: todos[todo_id]}
    def put(self,todo_id):
        todos[todo_id] = request.form['data']
        return {todo_id:todos[todo_id]}

class HelloWorld(Resource):
    def get(self):
        print 'hello world'
        return {'hello':'world'}, 201, {'Etag': 'some-opaque-string'}

api.add_resource(HelloWorld,'/')
api.add_resource(TodoSimple,'/<string:todo_id>')
api.add_resource(TodoList,'/todos')
api.add_resource(Todo,'/todos/<todo_id>')

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

curl http://localhost:5000/todos
curl http://localhost:5000/todos/todo3
curl http://localhost:5000/todos/todo2 -X DELETE -v
curl http://localhost:5000/todos -d "task=something new" -X POST -v
curl http://localhost:5000/todos/todo3 -d "task=something different" -X PUT -v

原文地址:https://www.cnblogs.com/jingbostar/p/6678682.html