use*_*881 8 python flask swagger swagger-codegen
我有兴趣将swagger-codegen
生成的Python服务器与现有的Flask应用程序集成. 从a swagger-codegen
生成基于Connexion
库的Python实现Swagger API specification
.
的例子我发现似乎都期望connexion.App
管理整个flask
应用程序.
import connexion
app = connexion.App(__name__, specification_dir='swagger/')
app.add_api('my_api.yaml')
app.run(port=8080)
Run Code Online (Sandbox Code Playgroud)
但是,我有现有的蓝图,配置和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)
Run Code Online (Sandbox Code Playgroud)
尝试搭载量大的定制Connexion Flask应用程序似乎比将裸露的蓝图集成connexion.Api
到我现有的Flask应用程序中更简单.但是,我不能轻易判断Connexion是否可以很好地与非Connexion管理蓝图配合使用.
在现有的传统Flask应用程序中集成Connexion Swagger定义的API的最佳方法是什么?有人走过这条路吗?
它可以创建connexion.App
,然后扩展Flask实例connexion.App(...).app
.
坚持使用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
Run Code Online (Sandbox Code Playgroud)