如何在Flask-RestX中定义Swagger的host字段?
问题描述
我正在使用Flask-RestX自动生成Swagger 2.0文档,但无法找到通过RestX定义host字段的方法。我希望生成包含"host": "myserver-prod.com.br"字段的swagger.json,但当前生成的文档缺少该字段,请求帮助实现此需求。
相关代码
app.py
from flask import Flask from flask import Blueprint from flask_restx import Api def create_app() -> Flask: """Create Flask app.""" app = Flask(__name__) # accepts both /endpoint and /endpoint/ as valid URLs app.url_map.strict_slashes = False app.register_blueprint(blueprint, url_prefix="/api/v1") return app blueprint = Blueprint("api", __name__) api = Api(blueprint, doc='/docs/', title="Test API", version="1.0", description="Test API") app = create_app() if __name__ == "__main__": # Only in dev app.run(host="0.0.0.0", port=8080, debug=True) # nosec
导出swagger.json的脚本
"""Export Swagger documentation automatically.""" import json import yaml from app import create_app def get_swagger_json(): """Get swagger json generated automatic by RestX.""" with app.test_client() as client: swagger_doc = client.get('/api/v1/swagger.json').get_json() with open('docs/specs/swagger.json', 'w', encoding='utf-8') as file: json.dump(swagger_doc, file, ensure_ascii=False, indent=4) app = create_app() get_swagger_json()
解决方案
Flask-RestX的Api类没有直接提供设置host字段的参数,你可以通过以下两种方式实现需求:
方式一:修改导出脚本手动添加host字段
直接在获取到swagger文档后,往字典中插入host字段再保存,这种方式适合仅在导出文档时指定生产环境host的场景:
def get_swagger_json(): """Get swagger json generated automatic by RestX.""" with app.test_client() as client: swagger_doc = client.get('/api/v1/swagger.json').get_json() # 添加host字段 swagger_doc['host'] = 'myserver-prod.com.br' with open('docs/specs/swagger.json', 'w', encoding='utf-8') as file: json.dump(swagger_doc, file, ensure_ascii=False, indent=4)
方式二:自定义Swagger规范生成逻辑
如果需要API运行时的swagger文档也显示host字段,可以通过RestX的自定义文档处理器实现:
blueprint = Blueprint("api", __name__) api = Api(blueprint, doc='/docs/', title="Test API", version="1.0", description="Test API") # 自定义swagger规范处理器 @api.documentation def custom_swagger(): swagger_doc = api.__schema__ swagger_doc['host'] = 'myserver-prod.com.br' return swagger_doc
这样无论是访问/api/v1/swagger.json还是通过导出脚本获取,都会包含指定的host字段。
注意事项
- 若API使用非标准端口,可在host字段中一并指定,例如
myserver-prod.com.br:8080 - 建议根据环境(开发/生产)通过环境变量动态设置host值,避免硬编码
内容的提问来源于stack exchange,提问作者natielle
相关产品推荐
相关产品推荐

