generate_openapi.py 9.0 KB

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