Flask---RESTful使用

Posted 进击的小猿

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Flask---RESTful使用相关的知识,希望对你有一定的参考价值。

整理于 Flask-RESTful官网

快速入门

from flask import Flask
from flask_restful import Resource, Api

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)

http://127.0.0.1:5000/输出如下:


    "hello": "world"

资源路由

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

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

todos = 

class TodoSimple(Resource):
    def get(self, todo_id):
        print(todo_id,"**************")
        return todo_id: todos.get(todo_id)

    def put(self, todo_id):
        todos[todo_id] = request.json['data']
        return todo_id: todos[todo_id]

api.add_resource(TodoSimple, '/<string:todo_id>')


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

put请求

get请求

Endpoints

很多时候在API中,你的资源将有多个URL。您可以将多个URL传递给Api对象add_resource()上的方法。每一个将被路由到你的Resource

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

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

todos = 

class TodoSimple(Resource):
    def get(self, post_id):
        print(post_id,"**************")
        if post_id:
            return post_id: post_id
        return 'hello': 'world'


    def put(self, todo_id):
        todos[todo_id] = request.json['data']
        return todo_id: todos[todo_id]

api.add_resource(TodoSimple, '/api/posts',
        '/api/posts/second/<string:post_id>',
        endpoint='restful_api_post')

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

数据格式化

from flask import Flask, request
from flask_restful import Resource, Api
from flask_restful import fields, marshal_with

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

resource_fields = 
    '_task':   fields.String,
    '_todo_id':fields.String,
    '_uri': fields.Url('todo_ep'),
    '_status': fields.String,



class TodoDao(object):
    def __init__(self, post_id, task):
        self.post_id = post_id
        self.task = task
        self.status = 'active'



class TodoSimple(Resource):
    @marshal_with(resource_fields)
    def get(self, post_id):
        return TodoDao(post_id=post_id, task='Remember the milk')



api.add_resource(TodoSimple, '/api/posts',
        '/api/posts/second/<string:post_id>',
        endpoint='todo_ep')


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

完整示例

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

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')


class Todo(Resource):
    def get(self, todo_id):
        print("todo_id",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 'True', 200

    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()
        print("args_%s"%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)

http://127.0.0.1:5000/todos (get方式)输出如下:


  "todo1": 
    "task": "build an API"
  ,
  "todo2": 
    "task": "?????"
  ,
  "todo3": 
    "task": "profit!"
  

http://localhost:5000/todos/todo1 (get方式)输出如下:


  "task": "build an API"

http://localhost:5000/todos/todo2 (delete)输出如下:

"True"

http://localhost:5000/todos (post)输出如下:
控制台args_‘task’: ‘我是task数据.’

http://localhost:5000/todos/2 (put请求)输出如下:

以上是关于Flask---RESTful使用的主要内容,如果未能解决你的问题,请参考以下文章

Flask restful api与blueprint结合实践

Flask (flask-restful) 和 MySQLdb (PyMySQL) 的奇怪并发问题

Flask 学习-23.restful 接口开发

Flask---RESTful使用

Flask RESTful 销毁用户令牌

Python Flask-Restful POST不接受JSON参数