generate_openapi.py 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241
  1. #!/usr/bin/env python3
  2. """Generate the current Flask route inventory as an OpenAPI 3.1 contract."""
  3. from __future__ import annotations
  4. import argparse
  5. import ast
  6. import json
  7. import re
  8. from collections import defaultdict
  9. from pathlib import Path
  10. ROOT = Path(__file__).resolve().parents[1]
  11. OUTPUT = ROOT / "docs" / "architecture" / "OPENAPI.yaml"
  12. PREFIXES = {
  13. "meta_data": "/api/meta",
  14. "data_interface": "/api/interface",
  15. "graph": "/api/graph",
  16. "system": "/api/system",
  17. "data_source": "/api/datasource",
  18. "data_development": "/api/development/v1",
  19. "data_flow": "/api/dataflow",
  20. "business_domain": "/api/bd",
  21. "data_factory": "/api/datafactory",
  22. "data_service": "/api/dataservice",
  23. "knowledge_base": "/api/knowledge",
  24. }
  25. SHORTHAND_METHODS = {"get", "post", "put", "patch", "delete"}
  26. RESPONSE_FIELDS = {
  27. ("knowledge_base", "ask"): [
  28. "query_id",
  29. "mode",
  30. "answer",
  31. "answer_status",
  32. "degraded_components",
  33. "citations",
  34. "evidence",
  35. "freshness_status",
  36. ],
  37. }
  38. def quoted(value: str) -> str:
  39. return json.dumps(value, ensure_ascii=False)
  40. def route_path(raw_path: str) -> tuple[str, list[dict[str, str]]]:
  41. parameters: list[dict[str, str]] = []
  42. def replace(match: re.Match[str]) -> str:
  43. converter = match.group(1) or "string"
  44. name = match.group(2)
  45. schema_type = "integer" if converter in {"int", "float"} else "string"
  46. parameters.append({"name": name, "type": schema_type})
  47. return "{" + name + "}"
  48. return re.sub(r"<(?:([a-zA-Z_]+):)?([a-zA-Z_][a-zA-Z0-9_]*)>", replace, raw_path), parameters
  49. def extract_routes() -> list[dict[str, object]]:
  50. routes: list[dict[str, object]] = []
  51. for module, prefix in PREFIXES.items():
  52. for route_file in sorted((ROOT / "app" / "api" / module).glob("*.py")):
  53. if route_file.name == "__init__.py":
  54. continue
  55. tree = ast.parse(route_file.read_text(encoding="utf-8"))
  56. for node in tree.body:
  57. if not isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)):
  58. continue
  59. for decorator in node.decorator_list:
  60. if not isinstance(decorator, ast.Call):
  61. continue
  62. function = decorator.func
  63. if not (
  64. isinstance(function, ast.Attribute)
  65. and isinstance(function.value, ast.Name)
  66. and function.value.id == "bp"
  67. and decorator.args
  68. ):
  69. continue
  70. if function.attr == "route":
  71. methods = ["GET"]
  72. for keyword in decorator.keywords:
  73. if keyword.arg == "methods":
  74. methods = ast.literal_eval(keyword.value)
  75. elif (
  76. module == "knowledge_base"
  77. and function.attr in SHORTHAND_METHODS
  78. ):
  79. methods = [function.attr.upper()]
  80. else:
  81. continue
  82. raw_path = ast.literal_eval(decorator.args[0])
  83. path, parameters = route_path(prefix + raw_path)
  84. summary = (ast.get_docstring(node) or node.name.replace("_", " ")).splitlines()[0]
  85. for method in methods:
  86. routes.append(
  87. {
  88. "path": path,
  89. "method": method.lower(),
  90. "tag": module,
  91. "operation_id": f"{module}_{node.name}_{method.lower()}",
  92. "summary": summary,
  93. "parameters": parameters,
  94. }
  95. )
  96. return sorted(routes, key=lambda item: (str(item["path"]), str(item["method"])))
  97. def render(routes: list[dict[str, object]]) -> str:
  98. by_path: dict[str, list[dict[str, object]]] = defaultdict(list)
  99. for route in routes:
  100. by_path[str(route["path"])].append(route)
  101. lines = [
  102. "openapi: 3.1.0",
  103. "info:",
  104. ' title: "DataOps Platform API(当前代码基线)"',
  105. ' version: "2026-07-16"',
  106. ' description: "由 scripts/generate_openapi.py 从 app/api/*/routes.py 生成。请求体与响应细节仍以现有专项 API 文档和代码为准。"',
  107. f"x-route-count: {len(routes)}",
  108. "servers:",
  109. ' - url: "http://localhost:15500"',
  110. ' description: "全本地隔离测试后端"',
  111. "tags:",
  112. ]
  113. for tag in PREFIXES:
  114. lines.extend([f" - name: {tag}", f" description: {quoted(PREFIXES[tag])}"])
  115. lines.append("paths:")
  116. for path, operations in sorted(by_path.items()):
  117. lines.append(f" {quoted(path)}:")
  118. for operation in operations:
  119. lines.extend(
  120. [
  121. f" {operation['method']}:",
  122. f" tags: [{operation['tag']}]",
  123. f" operationId: {operation['operation_id']}",
  124. f" summary: {quoted(str(operation['summary']))}",
  125. f" x-source: {quoted('app/api/' + str(operation['tag']) + '/routes.py')}",
  126. ]
  127. )
  128. parameters = operation["parameters"]
  129. if parameters:
  130. lines.append(" parameters:")
  131. for parameter in parameters:
  132. lines.extend(
  133. [
  134. f" - name: {parameter['name']}",
  135. " in: path",
  136. " required: true",
  137. " schema:",
  138. f" type: {parameter['type']}",
  139. ]
  140. )
  141. if operation["method"] in {"post", "put", "patch"}:
  142. lines.extend(
  143. [
  144. " requestBody:",
  145. " required: false",
  146. " content:",
  147. " application/json:",
  148. " schema:",
  149. " type: object",
  150. " additionalProperties: true",
  151. ]
  152. )
  153. response_fields = RESPONSE_FIELDS.get(
  154. (str(operation["tag"]), str(operation["operation_id"]).split("_")[-2])
  155. )
  156. if response_fields:
  157. lines.append(
  158. " x-response-fields: ["
  159. + ", ".join(response_fields)
  160. + "]"
  161. )
  162. lines.extend(
  163. [
  164. " responses:",
  165. ' "200":',
  166. ' description: "请求已由当前实现处理"',
  167. " content:",
  168. " application/json:",
  169. " schema:",
  170. " $ref: '#/components/schemas/ApiEnvelope'",
  171. " default:",
  172. ' description: "错误响应"',
  173. " content:",
  174. " application/json:",
  175. " schema:",
  176. " $ref: '#/components/schemas/ApiEnvelope'",
  177. ]
  178. )
  179. lines.extend(
  180. [
  181. "components:",
  182. " schemas:",
  183. " ApiEnvelope:",
  184. " type: object",
  185. " additionalProperties: true",
  186. " properties:",
  187. " success:",
  188. " type: boolean",
  189. " code:",
  190. " type: integer",
  191. " message:",
  192. " type: string",
  193. " data: {}",
  194. " timestamp:",
  195. " type: integer",
  196. " securitySchemes:",
  197. " bearerAuth:",
  198. " type: http",
  199. " scheme: bearer",
  200. " bearerFormat: JWT",
  201. " description: \"下一阶段统一认证方案;当前路由尚未全部接入。\"",
  202. ]
  203. )
  204. return "\n".join(lines) + "\n"
  205. def main(output: Path = OUTPUT) -> None:
  206. routes = extract_routes()
  207. if not routes:
  208. raise SystemExit("No Flask routes found")
  209. output.parent.mkdir(parents=True, exist_ok=True)
  210. output.write_text(render(routes), encoding="utf-8")
  211. try:
  212. label = output.relative_to(ROOT)
  213. except ValueError:
  214. label = output
  215. print(f"Generated {label} with {len(routes)} operations")
  216. if __name__ == "__main__":
  217. parser = argparse.ArgumentParser(description=__doc__)
  218. parser.add_argument("--output", type=Path, default=OUTPUT)
  219. args = parser.parse_args()
  220. main(args.output)