将 Swagger/OpenAPI 生成的 python 服务器与现有的 Flask 应用程序集成

Integrating Swagger/OpenAPI generated python server with existing Flask application

我有兴趣将 swagger-codegen 生成的 Python 服务器与现有的 Flask 应用程序集成。 swagger-codegen generates a Python implementation based on the Connexion library from a Swagger API specification.

examples I have found all seem to expect that connexion.App 管理整个 flask 应用程序。

import connexion

app = connexion.App(__name__, specification_dir='swagger/')
app.add_api('my_api.yaml')
app.run(port=8080)

但是,我有现有的蓝图、配置和 sqlalchemy 模型,我想与生成的 Connexion API 集成。看起来 connexion.App.app 是基础 Flask 应用程序。一种选择可能是进入并扩展 Connexion Flask 应用程序,可能是这样的:

import connexion

app = connexion.App(__name__, specification_dir='swagger/')

app.app.config.from_pyfile('...')
db.init_app(app.app)
for blueprint in my_blueprints:
    app.app.register_blueprint(blueprint)

app.add_api('my_api.yaml')

app.run(port=8080)

尝试搭载高度自定义的 Connexion Flask 应用程序似乎比将 connexion.Api 的裸蓝图集成到我现有的 Flask 应用程序中更简单。但是,我无法轻易判断 Connexion 是否旨在与非 Connexion 管理的蓝图很好地配合使用。

将 API 定义的 Connexion Swagger 集成到现有的传统 Flask 应用程序中的最佳方式是什么?有人走过这条路吗?

它可以创建 connexion.App 然后从 connexion.App(...).app 扩展 Flask 实例。

坚持使用 Application Factory 是最简单的。除了是一个普遍有用的模式之外,它还与生成的测试很好地集成。

一个问题是控制器似乎期望连接模型,特别是在启用响应验证的情况下,但默认 JSON 序列化程序不处理它们。该模型带有一个 JSONEncoder class 有助于模型序列化,但它需要在 create_app.

中连接
def create_app():
    connexionApp = connexion.App(__name__, specification_dir='swagger')
    app = connexionApp.app

    # This allows the connexion models to be serialized to JSON    
    app.json_encoder = JSONEncoder

    # normal configuration

    # The return value is a `connexion.Api`.
    # If needed, the api blueprint is available at `connexion.Api.blueprint`
    connexionApp.add_api('swagger.yaml')

    return app