Flasgger 是一个用于生成 Swagger API 文档的 Flask 扩展。要通过 Flasgger 设置常用的 Swagger 配置,你可以在初始化 Flasgger 时传递一个配置字典。
如下例:
from flask import Flask, jsonify
from flasgger import Swagger
app = Flask(__name__)
# 设置 Flasgger 配置
app.config["SWAGGER"] = {
"title": "My API Documentation",
"description": "This is the documentation for my API.",
"version": "1.0.0",
"termsOfService": "https://example.com/terms",
"contact": {
"name": "MrSun",
"email": "MrSun@example.com",
# "url": "https://example.com"
},
"license": {
"name": "MIT",
"url": "https://opensource.org/licenses/MIT"
},
"host": "http://127.0.0.1:5000",
"basePath": "/v1",
"schemes": ["https"],
"definitions": {
"ResponseMode": {
"type": "object",
"properties": {
"code": {
"type": "integer",
"format": "int64",
"description": "状态码",
"required": "true"
},
"desc": {
"type": "string",
"description": "状态码说明",
"required": "true"
},
"dataObject": {
"type": "object",
"description": "业务数据节点",
"required": "true"
}
}
}
}
}
# 初始化 Flasgger
Swagger(app)
@app.route("/index")
def index():
"""
门户
---
tags:
- entry
responses:
200:
description: 成功响应
schema:
$ref: '#/definitions/ResponseMode'
:return:
"""
return jsonify({"dataObject": {}, "code": 0, "desc": "成功"})
if __name__ == "__main__":
app.run(debug=True)
"""
if __name__ == "__main__":
app.run(debug=True)
以下是每个字段的说明:
在上面的示例中,我们使用 app.config["SWAGGER"]
字典来设置 Flasgger 的常用配置选项。以下是每个字段的说明:
1. title
:API 文档的标题。
"title": "My API Documentation"
2. description
:API 文档的描述。
"description": "This is the documentation for my API."
3. version
:API 的版本号。
"version": "1.0.0"
4. termsOfService
:API 的服务条款 URL。
"termsOfService": "https://example.com/terms"
5. contact
:API 作者的联系信息。
"contact": {
"name": "John Doe",
"email": "john.doe@example.com",
"url": "https://example.com"
}
6. license
:API 的许可证信息。
"license": {
"name": "MIT",
"url": "https://opensource.org/licenses/MIT"
}
7. host
:API 服务器的主机名。
"host": "api.example.com"
8. basePath
:API 的基本路径【在flasgger中实践发现失效】。
"basePath": "/v1"
9. schemes
:API 支持的协议(如 http
、https
等)。
"schemes": ["https"]
10. definitions
:定义 API 的数据模型。
"definitions": {
"ResponseMode": {
"type": "object",
"properties": {
"code": {
"type": "integer",
"format": "int64",
"description": "状态码",
"required": "true"
},
"desc": {
"type": "string",
"description": "状态码说明",
"required": "true"
},
"dataObject": {
"type": "object",
"description": "业务数据节点",
"required": "true"
}
}
}
}
在这个示例中,我们设置了 API 文档的标题、描述、版本号、服务条款、联系信息、许可证信息、主机名、基本路径、协议和标签等配置选项。这些配置选项将出现在生成的 Swagger API 文档中,可以帮助用户更好地理解和使用你的 API。在实际项目中,你可以根据需要添加或修改这些配置选项,以满足你的 API 文档需求。
原文始发于微信公众号(Python小白养成记):Flasgger之初始化常用配置
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/290745.html