You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

SpecTree 1.2.8能否隐藏Flask项目中指定端点的Swagger UI展示?

在Spectree 1.2.8中隐藏特定路由不显示在Swagger UI

针对你的需求,Spectree 1.2.8没有直接提供隐藏指定路由的配置项,但可以通过以下几种方案实现:

方法1:标签过滤(轻量方案)

给私有路由添加专属标签,然后在Swagger UI配置中默认隐藏该标签的内容:

  • 给私有路由标记专属标签:
from spectree import SpecTree

api = SpecTree('flask')

@api.validate(tags=['internal'])
@app.route('/private-endpoint')
def private_route():
    return {"message": "private content"}
  • 初始化Spectree时传入UI过滤配置:
api = SpecTree(
    'flask',
    swagger_ui_config={
        'filter': True,  # 开启标签过滤功能
        'defaultFilter': '-internal'  # 默认隐藏带internal标签的路由
    }
)

用户打开Swagger UI时默认看不到私有路由,手动取消过滤后才能查看,兼顾校验和隐私需求。

方法2:自定义文档生成(彻底移除)

如果需要完全从OpenAPI文档中删除私有路由,可以继承SpecTree类重写文档生成逻辑:

from spectree import SpecTree

class CustomSpecTree(SpecTree):
    def generate_doc(self):
        # 先获取默认生成的文档
        openapi_doc = super().generate_doc()
        # 移除指定路径的路由
        private_paths = ['/private-endpoint', '/admin/secret']
        for path in private_paths:
            if path in openapi_doc['paths']:
                del openapi_doc['paths'][path]
        return openapi_doc

# 使用自定义类初始化
api = CustomSpecTree('flask')

这种方式会直接从生成的OpenAPI规范中删除目标路由,Swagger UI完全不会显示它们。

方法3:分离实例(物理隔离)

创建两个Spectree实例,一个用于公开路由(挂载Swagger UI),另一个仅用于私有路由的校验:

# 公开API实例,挂载Swagger UI
public_api = SpecTree('flask', path='/swagger')

# 私有API实例,不挂载UI
private_api = SpecTree('flask')

# 公开路由使用public_api校验
@public_api.validate()
@app.route('/public-endpoint')
def public_route():
    return {"message": "public content"}

# 私有路由使用private_api校验,不会出现在Swagger UI中
@private_api.validate()
@app.route('/private-endpoint')
def private_route():
    return {"message": "private content"}

私有路由的校验逻辑正常生效,但完全独立于公开的文档体系。

内容的提问来源于stack exchange,提问作者Nadav

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.29 11:42:12