generate_openapi.py 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211
  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 ast
  5. import argparse
  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. }
  24. def quoted(value: str) -> str:
  25. return json.dumps(value, ensure_ascii=False)
  26. def route_path(raw_path: str) -> tuple[str, list[dict[str, str]]]:
  27. parameters: list[dict[str, str]] = []
  28. def replace(match: re.Match[str]) -> str:
  29. converter = match.group(1) or "string"
  30. name = match.group(2)
  31. schema_type = "integer" if converter in {"int", "float"} else "string"
  32. parameters.append({"name": name, "type": schema_type})
  33. return "{" + name + "}"
  34. return re.sub(r"<(?:([a-zA-Z_]+):)?([a-zA-Z_][a-zA-Z0-9_]*)>", replace, raw_path), parameters
  35. def extract_routes() -> list[dict[str, object]]:
  36. routes: list[dict[str, object]] = []
  37. for module, prefix in PREFIXES.items():
  38. for route_file in sorted((ROOT / "app" / "api" / module).glob("*.py")):
  39. if route_file.name == "__init__.py":
  40. continue
  41. tree = ast.parse(route_file.read_text(encoding="utf-8"))
  42. for node in tree.body:
  43. if not isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)):
  44. continue
  45. for decorator in node.decorator_list:
  46. if not isinstance(decorator, ast.Call):
  47. continue
  48. function = decorator.func
  49. if not (
  50. isinstance(function, ast.Attribute)
  51. and function.attr == "route"
  52. and isinstance(function.value, ast.Name)
  53. and function.value.id == "bp"
  54. and decorator.args
  55. ):
  56. continue
  57. raw_path = ast.literal_eval(decorator.args[0])
  58. methods = ["GET"]
  59. for keyword in decorator.keywords:
  60. if keyword.arg == "methods":
  61. methods = ast.literal_eval(keyword.value)
  62. path, parameters = route_path(prefix + raw_path)
  63. summary = (ast.get_docstring(node) or node.name.replace("_", " ")).splitlines()[0]
  64. for method in methods:
  65. routes.append(
  66. {
  67. "path": path,
  68. "method": method.lower(),
  69. "tag": module,
  70. "operation_id": f"{module}_{node.name}_{method.lower()}",
  71. "summary": summary,
  72. "parameters": parameters,
  73. }
  74. )
  75. return sorted(routes, key=lambda item: (str(item["path"]), str(item["method"])))
  76. def render(routes: list[dict[str, object]]) -> str:
  77. by_path: dict[str, list[dict[str, object]]] = defaultdict(list)
  78. for route in routes:
  79. by_path[str(route["path"])].append(route)
  80. lines = [
  81. "openapi: 3.1.0",
  82. "info:",
  83. ' title: "DataOps Platform API(当前代码基线)"',
  84. ' version: "2026-07-16"',
  85. ' description: "由 scripts/generate_openapi.py 从 app/api/*/routes.py 生成。请求体与响应细节仍以现有专项 API 文档和代码为准。"',
  86. f"x-route-count: {len(routes)}",
  87. "servers:",
  88. ' - url: "http://localhost:15500"',
  89. ' description: "全本地隔离测试后端"',
  90. "tags:",
  91. ]
  92. for tag in PREFIXES:
  93. lines.extend([f" - name: {tag}", f" description: {quoted(PREFIXES[tag])}"])
  94. lines.append("paths:")
  95. for path, operations in sorted(by_path.items()):
  96. lines.append(f" {quoted(path)}:")
  97. for operation in operations:
  98. lines.extend(
  99. [
  100. f" {operation['method']}:",
  101. f" tags: [{operation['tag']}]",
  102. f" operationId: {operation['operation_id']}",
  103. f" summary: {quoted(str(operation['summary']))}",
  104. f" x-source: {quoted('app/api/' + str(operation['tag']) + '/routes.py')}",
  105. ]
  106. )
  107. parameters = operation["parameters"]
  108. if parameters:
  109. lines.append(" parameters:")
  110. for parameter in parameters:
  111. lines.extend(
  112. [
  113. f" - name: {parameter['name']}",
  114. " in: path",
  115. " required: true",
  116. " schema:",
  117. f" type: {parameter['type']}",
  118. ]
  119. )
  120. if operation["method"] in {"post", "put", "patch"}:
  121. lines.extend(
  122. [
  123. " requestBody:",
  124. " required: false",
  125. " content:",
  126. " application/json:",
  127. " schema:",
  128. " type: object",
  129. " additionalProperties: true",
  130. ]
  131. )
  132. lines.extend(
  133. [
  134. " responses:",
  135. ' "200":',
  136. ' description: "请求已由当前实现处理"',
  137. " content:",
  138. " application/json:",
  139. " schema:",
  140. " $ref: '#/components/schemas/ApiEnvelope'",
  141. " default:",
  142. ' description: "错误响应"',
  143. " content:",
  144. " application/json:",
  145. " schema:",
  146. " $ref: '#/components/schemas/ApiEnvelope'",
  147. ]
  148. )
  149. lines.extend(
  150. [
  151. "components:",
  152. " schemas:",
  153. " ApiEnvelope:",
  154. " type: object",
  155. " additionalProperties: true",
  156. " properties:",
  157. " success:",
  158. " type: boolean",
  159. " code:",
  160. " type: integer",
  161. " message:",
  162. " type: string",
  163. " data: {}",
  164. " timestamp:",
  165. " type: integer",
  166. " securitySchemes:",
  167. " bearerAuth:",
  168. " type: http",
  169. " scheme: bearer",
  170. " bearerFormat: JWT",
  171. " description: \"下一阶段统一认证方案;当前路由尚未全部接入。\"",
  172. ]
  173. )
  174. return "\n".join(lines) + "\n"
  175. def main(output: Path = OUTPUT) -> None:
  176. routes = extract_routes()
  177. if not routes:
  178. raise SystemExit("No Flask routes found")
  179. output.parent.mkdir(parents=True, exist_ok=True)
  180. output.write_text(render(routes), encoding="utf-8")
  181. try:
  182. label = output.relative_to(ROOT)
  183. except ValueError:
  184. label = output
  185. print(f"Generated {label} with {len(routes)} operations")
  186. if __name__ == "__main__":
  187. parser = argparse.ArgumentParser(description=__doc__)
  188. parser.add_argument("--output", type=Path, default=OUTPUT)
  189. args = parser.parse_args()
  190. main(args.output)