import logging import json from typing import Dict, Any, Optional class SchemaProvider: def __init__(self, global_api_spec: Dict[str, Any]): self.global_api_spec = global_api_spec self.logger = logging.getLogger(__name__) def get_schema(self, endpoint_spec: Dict[str, Any], status_code: int) -> Optional[Dict]: """ 获取端点在特定状态码下的响应Schema。 当前实现:从API规范中查找。 未来可扩展:优先从动态映射中获取,如果失败或未配置,则回退到当前实现。 """ # --- 预留的动态获取逻辑扩展点 --- # if self._use_dynamic_provider(endpoint_spec): # schema = self._fetch_dynamic_schema(endpoint_spec) # if schema: # return schema # --------------------------------- return self._get_schema_from_spec(endpoint_spec, status_code) def _get_schema_from_spec(self, endpoint_spec: Dict[str, Any], status_code: int) -> Optional[Dict]: """ (私有方法) 从API规范中提取Schema,这是当前版本的主要实现。 """ self.logger.debug(f"尝试从API规范中为状态码 {status_code} 查找Schema。") expected_schema = None # 兼容 OpenAPI/Swagger 格式 if 'responses' in endpoint_spec: responses = endpoint_spec['responses'] # 优先匹配精确的状态码 if str(status_code) in responses: response_def = responses[str(status_code)] if 'content' in response_def and 'application/json' in response_def['content']: expected_schema = response_def['content']['application/json'].get('schema') # 回退到 'default' elif 'default' in responses: response_def = responses['default'] if 'content' in response_def and 'application/json' in response_def['content']: expected_schema = response_def['content']['application/json'].get('schema') # 兼容 YAPI 格式 (简化) elif 'res_body_type' in endpoint_spec and endpoint_spec['res_body_type'] == 'json': if endpoint_spec.get('res_body_is_json_schema') and endpoint_spec.get('res_body'): try: expected_schema = json.loads(endpoint_spec['res_body']) except (json.JSONDecodeError, TypeError): self.logger.error(f"从YAPI res_body解析JSON schema失败。res_body: {endpoint_spec['res_body']}") return None # 解析失败 if not expected_schema: self.logger.info(f"在API规范中未找到针对状态码 {status_code} 的JSON schema。") return expected_schema