Python flask-restful框架讲解

Restful 是 Flask 的扩展,增加了对快速构建 REST api 的支持。它是一个轻量级的概念,与您现有的 ORM/librarie 一起工作。Restful 鼓励最小化设置的最佳实践。如果你熟悉Flask,Flask-RESTful 应该很容易。
关于flask的使用,参考我的之前的博客:https://blog.csdn.net/shifengboy/article/details/114274271

flask-restful官方文档:https://flask-restful.readthedocs.io/en/lates
中文文档:

flask-restful 安装 pip install 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, 'http://www.likecs.com/') if __name__ == '__main__': app.run(debug=True)

运行结果:

$ curl :5000/ {"hello": "world"} Resourceful 路由

Flask-RESTful 提供的主要构建块是资源。资源构建在 Flask 可插入视图之上,只需在资源上定义方法,就可以轻松访问多个 HTTP 方法。一个 todo 应用程序的基本 CRUD 资源是这样的:

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): return {todo_id: todos[todo_id]} def put(self, todo_id): todos[todo_id] = request.form['data'] return {todo_id: todos[todo_id]} api.add_resource(TodoSimple, '/<string:todo_id>') if __name__ == '__main__': app.run(debug=True)

运行结果:

chenshifengdeMacBook-Pro:~ chenshifeng$ curl :5000/todo1 -d "data=Remember the milk" -X PUT { "todo1": "Remember the milk" } chenshifengdeMacBook-Pro:~ chenshifeng$ curl :5000/todo1 { "todo1": "Remember the milk" } chenshifengdeMacBook-Pro:~ chenshifeng$ curl :5000/todo2 -d "data=Change my brakepads" -X PUT { "todo2": "Change my brakepads" } chenshifengdeMacBook-Pro:~ chenshifeng$ curl :5000/todo2 { "todo2": "Change my brakepads" } chenshifengdeMacBook-Pro:~ chenshifeng$

Restful 能够从 view 方法中理解多种返回值。类似于 Flask,你可以返回任何可迭代的并且它将被转换成一个响应,包括原始 Flask 响应对象。还支持使用多个返回值设置响应代码和响应头,如下所示:

#!/usr/bin/python # -*- coding: UTF-8 -*- """ @author:chenshifeng @file:flask_restful_demo.py @time:2021/03/05 """ from flask import Flask, request from flask_restful import Resource, Api app = Flask(__name__) api = Api(app) class Todo1(Resource): def get(self): # Default to 200 OK return {'task': 'Hello world'} class Todo2(Resource): def get(self): # Set the response code to 201 return {'task': 'Hello world'}, 201 class Todo3(Resource): def get(self): # Set the response code to 201 and return custom headers return {'task': 'Hello world'}, 201, {'Etag': 'some-opaque-string'} api.add_resource(Todo1,'/todo1') api.add_resource(Todo2,'/todo2') api.add_resource(Todo3,'/todo3') if __name__ == '__main__': app.run(debug=True)

运行结果:

chenshifengdeMacBook-Pro:~ chenshifeng$ curl -i :5000/todo1 HTTP/1.0 200 OK Content-Type: application/json Content-Length: 30 Server: Werkzeug/1.0.1 Python/3.9.2 Date: Fri, 05 Mar 2021 16:08:28 GMT { "task": "Hello world" } chenshifengdeMacBook-Pro:~ chenshifeng$ curl -i :5000/todo2 HTTP/1.0 201 CREATED Content-Type: application/json Content-Length: 30 Server: Werkzeug/1.0.1 Python/3.9.2 Date: Fri, 05 Mar 2021 16:08:32 GMT { "task": "Hello world" } chenshifengdeMacBook-Pro:~ chenshifeng$ curl -i :5000/todo3 HTTP/1.0 201 CREATED Content-Type: application/json Content-Length: 30 Etag: some-opaque-string Server: Werkzeug/1.0.1 Python/3.9.2 Date: Fri, 05 Mar 2021 16:08:34 GMT { "task": "Hello world" } chenshifengdeMacBook-Pro:~ chenshifeng$ Endpoints 端点

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

api.add_resource(HelloWorld, 'http://www.likecs.com/', '/hello')

您还可以将路径的某些部分作为变量匹配到Resource。

api.add_resource(Todo, '/todo/<int:todo_id>', endpoint='todo_ep')

演示代码:

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'} class Todo(Resource): def get(self, todo_id): # Default to 200 OK return {'task': 'Hello world'} api.add_resource(HelloWorld, 'http://www.likecs.com/', '/hello') api.add_resource(Todo, '/todo/<int:todo_id>', endpoint='todo_ep') if __name__ == '__main__': app.run(debug=True)

演示结果:

chenshifengdeMacBook-Pro:~ chenshifeng$ curl :5000/ { "hello": "world" } chenshifengdeMacBook-Pro:~ chenshifeng$ curl :5000/hello { "hello": "world" } chenshifengdeMacBook-Pro:~ chenshifeng$ curl :5000/todo/1 { "task": "Hello world" } chenshifengdeMacBook-Pro:~ chenshifeng$ curl :5000/todo/2 { "task": "Hello world" } 参数解析

虽然 Flask 可以方便地访问请求数据(即 querystring 或 POST 表单编码的数据) ,但验证表单数据仍然是一件痛苦的事情。使用类似于 argparse 的库对请求数据验证提供内置支持。

from flask import Flask from flask_restful import reqparse, Api, Resource app = Flask(__name__) api = Api(app) parser = reqparse.RequestParser() parser.add_argument('rate', type=int, help='Rate to charge for this resource') class Todo(Resource): def post(self): args = parser.parse_args() print(args) # Default to 200 OK return {'task': 'Hello world'} api.add_resource(Todo,'/todos' ) if __name__ == '__main__': app.run(debug=True) chenshifengdeMacBook-Pro:~ chenshifeng$ curl -d 'rate=100' :5000/todos { "task": "Hello world" } chenshifengdeMacBook-Pro:~ chenshifeng$ curl -d 'rate=foo' :5000/todos { "message": { "rate": "Rate to charge for this resource" } }

与 argparse 模块不同,reqparse. RequestParser.parse _ args ()返回 Python 字典,而不是自定义数据结构。

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/wsswxd.html