首页 文章

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

提问于
浏览
7

我有兴趣将 swagger-codegen 生成的Python服务器与现有的Flask应用程序集成 . swagger-codegen基于Swagger API specification中的Connexion库生成Python实现 .

examples我发现所有人似乎都期望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管理蓝图配合使用 .

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

1 回答

  • 5

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

    坚持Application Factory是最容易的 . 除了是一种通用的模式之外,它还与生成的测试很好地集成 .

    一个问题是连接模型似乎是从控制器中预期的,特别是如果启用了响应验证,但它们不是由默认的JSON序列化程序处理的 . 该模型附带了一个 JSONEncoder 类,可以帮助进行模型序列化,但需要在 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
    

相关问题