如何通过flask-restx用x-tagGroups区分内外资源并生成公开接口文档?
解决思路
针对你需要归集内部操作、仅生成公开接口文档,且想批量给Namespace标记内部属性的需求,提供以下几个可行方案:
一、批量给整个Namespace标记内部属性
不用逐个端点手动添加vendor扩展,通过批量处理或自定义Namespace类实现自动标记:
1. 批量遍历Namespace操作添加标记
创建Namespace后,遍历其下所有操作统一添加内部标识:
from flask_restx import Namespace, Resource def mark_namespace_internal(namespace): # 遍历命名空间下所有操作 for operation in namespace.operations.values(): operation.vendor_extensions['x-internal-endpoint'] = 'true' # 创建内部命名空间并标记 internal_ns = Namespace("Internal", path="/api/v1/internal") mark_namespace_internal(internal_ns) # 该命名空间下的所有操作自动带上内部标识 @internal_ns.route('/test') class MyResource(Resource): def get(self): return {"message": "internal test"}
2. 自定义InternalNamespace类(更优雅)
继承原Namespace类,重写资源添加方法,自动给所有操作加标记:
from flask_restx import Namespace as OriginalNamespace, Resource class InternalNamespace(OriginalNamespace): def add_resource(self, resource, *urls, **kwargs): super().add_resource(resource, *urls, **kwargs) # 遍历资源的所有请求方法,给对应操作加内部标识 for method in resource.methods: op_id = f"{resource.__name__.lower()}_{method.lower()}" if op_id in self.operations: self.operations[op_id].vendor_extensions['x-internal-endpoint'] = 'true' # 使用自定义命名空间,无需手动标记每个操作 internal_ns = InternalNamespace("Internal", path="/api/v1/internal") @internal_ns.route('/test') class MyResource(Resource): def get(self): return {"message": "internal test"}
二、生成文档时过滤内部操作
不管用哪种标记方式,最终可以通过修改OpenAPI Spec来过滤内部操作,生成纯公开文档:
from flask_restx import Api def get_public_api_spec(api): spec = api.__schema__.copy() # 遍历所有路径,删除标记为内部的操作 for path, path_ops in list(spec['paths'].items()): for method, op in list(path_ops.items()): if op.get('x-internal-endpoint') == 'true': del path_ops[method] # 如果路径下无剩余操作,删除整个路径 if not path_ops: del spec['paths'][path] # 可选:过滤内部标签(如果用了复合标签如Internal/Resource1) if 'tags' in spec: spec['tags'] = [tag for tag in spec['tags'] if not tag['name'].startswith('Internal/')] return spec # 假设api是你的Api实例 public_spec = get_public_api_spec(api) # 可将public_spec保存为文件或传给Swagger UI展示
三、模拟x-tagGroups分组(若需分组而非过滤)
如果只是想在文档中分组展示内外操作,可手动给OpenAPI Spec添加x-tagGroups扩展(需Swagger UI/Redoc支持该扩展):
api = Api(app, title="API文档") # 手动添加标签分组配置 api.__schema__['x-tagGroups'] = [ { "name": "公开操作", "tags": ["Public", "Tickets", "Events"] }, { "name": "内部操作", "tags": ["Internal/Resource1", "Internal/Resource2"] } ]
内容的提问来源于stack exchange,提问作者canelle
相关产品推荐
相关产品推荐

