使用 Flask-Restplus、API 和多个蓝图大摇大摆

Swagger with Flask-Restplus, API and multiple Blueprints

我正在使用 Flask 和 Flask-Restplus 构建一个非常复杂的微服务。
它将有很多端点,因此我将每个端点组织到一个单独的蓝图中。

下面的示例代码和目录结构应该可以让您对我的想法有所了解:

.
├── endpoints
│   ├── endpointa.py
│   ├── endpointb.py
│   ├── endpointc.py
│   └── __init__.py
├── __init__.py
└── run.py

我的主要 init.py 看起来像这样:

from flask import Flask, Blueprint, logging, jsonify, request, Response
from flask_restplus import Resource, Api   


# create app and api
app = Flask(__name__)
api_prefix  = '/api/v1/'

# register Blueprints
from endpoints.endpointa import endpointa_api
app.register_blueprint(endpointa_api, url_prefix=api_prefix)

from endpoints.endpointb import endpointb_api
app.register_blueprint(endpointb_api, url_prefix=api_prefix)

from endpoints.endpointc import endpointc_api
app.register_blueprint(endpointc_api, url_prefix=api_prefix)


api = Api(app,
          version='1',
          title='Test Service REST-API',
          description='A REST-API for the Test Service, implemented in python')


if __name__ == '__main__':
    app.run(debug=True, host="0.0.0.0", port=5060)

endpointa.py对应蓝图:

from os import environ
import json, ast, syslog
import requests
import gc
from flask import Flask, Blueprint, logging, jsonify, request, Response
from flask_restplus import Resource, Api

endpointa_api = Blueprint('endpointa_api', __name__)

@endpointa_api.route('testa', methods=['GET'])
def testa():
    ...


@endpointa_api.route('testa/<string:testa_id>', methods=['GET', 'POST'])
def testa_id():
    ...

再次:

我可以通过邮递员访问我的端点,但是 swagger-UI 没有显示任何内容:

通常我会使用类似

的方式将端点添加到 API
api.add_resource(TestClass, api_prefix + 'test')

但这对于多个蓝图似乎是不可能的。

谁能告诉我如何 add/register 这些蓝图(endpointa_api、endpointb_api 和 endpointc_api)与 Api ?

使用 Flask-Restplus 有 2 种可能的解决方案:

  • 使用 Flask-RestPlus 命名空间
  • 将您的蓝图变成 Flask-RestPlus Apis

您可以在文档中阅读有关两者的信息: https://flask-restplus.readthedocs.io/en/stable/scaling.html

命名空间

Flask-RESTPlus provides a way to use almost the same pattern as Flask’s blueprint. The main idea is to split your app into reusable namespaces.

from flask_restplus import Api

from .namespace1 import api as ns1
from .namespace2 import api as ns2
# ...
from .namespaceX import api as nsX

api = Api(
    title='My Title',
    version='1.0',
    description='A description',
    # All API metadatas
)

api.add_namespace(ns1)
api.add_namespace(ns2)
# ...
api.add_namespace(nsX)

蓝图 API

Here’s an example of how to link an Api up to a Blueprint.

from flask import Blueprint
from flask_restplus import Api

blueprint = Blueprint('api', __name__)
api = Api(blueprint)
# ...

Using a blueprint will allow you to mount your API on any url prefix and/or subdomain in you application:

from flask import Flask
from apis import blueprint as api

app = Flask(__name__)
app.register_blueprint(api, url_prefix='/api/1')
app.run(debug=True)