Loading... <div class="tip share">请注意,本文编写于 567 天前,最后修改于 562 天前,其中某些信息可能已经过时。</div> ## 简介 **flask-restx**是一个支持**RESTFul**的flask插件。 用于规范化接口的编写,并且支持 **swagger**文档。 > [github地址 官方文档地址][1] <!--more--> ## 使用说明 ### 下载 ```shell pip install flask-restx ``` ### 示例代码 示例代码以一个使用蓝图的程序为例。其他小的应用可参看 [**flask-restx官方示例**][2] #### 项目结构 ``` . ├── config.py ├── log ├── manage.py # 启动入口 ├── server │ ├── __init__.py │ ├── api.py │ ├── apis │ │ └── test │ │ ├── api.py │ │ └── web.py │ ├── static │ └── templates └── utils └── db.py ``` #### Demo: - server __init__.py ```python from flask import Flask def create_app(): # 创建Flask对象 app = Flask(__name__) # 注册蓝图 from server.api import api_v1 app.register_blueprint(api_v1) return app ``` - server api.py ```python from flask import Blueprint from flask_restx import Api from server.apis.test.web import ns as test_ns api_v1 = Blueprint('api1', __name__, url_prefix='/api') api = Api( api_v1, version='1.0', title='test flask', description='test flask' ) api.add_namespace(test_ns) ``` - server apis test web.py ```python import json from flask import request, render_template, make_response, jsonify from flask_restx import Namespace, Resource, fields ns = Namespace('test', description='test') @ns.route("", strict_slashes=False) # 实际访问地址 /api/test/ class TestHandler(Resource): def get(self): # 如果使用模板的块,需要使用 make_response # return make_response(render_template('index.html', data=res), 200) # 使用 jsonify 是为了返回json数据的同时,相比于 json.dumps() 其会自动修改 content-type 为 application/json # 另外,如果使用 jsonify()的同时,还想自定义返回状态码,可以使用 make_response(jsonify(data=data), 201) return jsonify() def post(self): pass def put(self): pass def delete(self): pass ``` #### 代码说明 1. 使用 **flask-restx** 之后,可以使用类视图的方式定义接口。 2. 可以访问 **localhost:5000/api** 访问 **swagger** 接口文档页面。 3. 接口文档可以在编写代码的地方一起定义。 #### swagger文档编写方式 以上面 **TestHandler** 类方法为基础,定义以下较为常用的文档。 > 通常情况下,**restful** 接口默认返回的都是 **json** 数据。因此以下文档针对 **json** 数据。 > 所有定义文档都可以在浏览器访问 **/api/** 查看 > 对于前后端不分离的 **templates** 等模板文档,可能有不正确的地方。 - 参数以url形式 ```python @ns.route("/<id>", strict_slashes=False) # 实际访问地址 /api/test/1 @ns.doc(params={'id': 'An ID'}) class TestHandler(Resource): def get(self, id): return jsonify() @ns.doc(response={403: 'Not Authorized'}) def post(self, id): pass ``` - 参数以json body的形式 ```python parent = ns.model('Parent', { 'name': fields.String, 'age': fields.Integer(discriminator=True), 'addr': fields.String(description='地址'), 'gender': fields.String(description='性别', required=True, enum=['男', '女', '未知']) }) child = ns.inherit('Child', parent, { 'extra': fields.String }) @ns.route("/test3", strict_slashes=False) # /api/test/test3 class Test2Handler(Resource): @ns.marshal_with(child, as_list=True) # 等价于 @api.marshal_list_with(resource_fields) def get(self): return "返回一个对象" @ns.marshal_with(child, code=201) # 201 代表创建成功 def post(self): return '创建一个对象成功', 201 ``` - 其他 **flask-restx** 提供了许多文档定制功能。每个功能都有不同的写法。如: 1. 某个请求默认需要某些参数,并且要验证 ===>**@ns.expect(resource_fields, validate=True)** 2. 给已知响应定义默认响应-- **@ns.response()** 3. url路径文档===》**@ns.route('', doc='')** 或者 **@ns.doc()** 4. 可使用多个 **@ns.route()** 装饰一个函数,使得多个 **url** 定位到一个Handler处理 5. 给参数定义文档。如上文的 **json body** 形式中的 **parent** 6.给 **method** 定义文档 7.定义 **headers** 定义文档 6. 隐藏某些文档 7. 文档授权 10.其他 > 具体文档可点 [**flask-restx官方文档**][3] 了解 ## RESTful接口风格说明 具体说明可参看[阮一峰博客][4] 坑点:此接口风格对批量处理的支持并不友好。解决此问题可参看[RESTful API批量操作的实现][5] [1]: https://flask-restx.readthedocs.io/en/latest/ [2]: https://github.com/python-restx/flask-restx/tree/master/examples [3]: https://flask-restx.readthedocs.io/en/latest/swagger.html [4]: https://www.ruanyifeng.com/blog/2018/10/restful-api-best-practices.html [5]: https://www.jianshu.com/p/448e222a8c37 Last modification:July 27, 2021 © Allow specification reprint Support Appreciate the author AliPayWeChat Like 0 如果觉得我的文章对你有用,请作者喝杯咖啡把~