本文主要是介绍Flask---RESTful使用,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
-
-
- 快速入门
- 资源路由
- Endpoints
- 数据格式化
- 完整示例
-
整理于 Flask-RESTful官网
快速入门
from flask import Flask
from flask_restful import Resource, Apiapp = 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, Apiapp = 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, Apiapp = 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_withapp = 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_idself.task = taskself.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, Resourceapp = 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', 200def put(self, todo_id):args = parser.parse_args()task = {'task': args['task']}TODOS[todo_id] = taskreturn task, 201class TodoList(Resource):def get(self):return TODOSdef post(self):args = parser.parse_args()print("args_%s"%args)todo_id = int(max(TODOS.keys()).lstrip('todo')) + 1todo_id = 'todo%i' % todo_idTODOS[todo_id] = {'task': args['task']}return TODOS[todo_id], 201api.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使用的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!