#!/usr/bin/env python3 """ backend/scripts/migrate_jsonify_errors.py 用途:将 API 层 return jsonify({'error': ...}), 4xx 批量改写为 raise AppError 子类。 逻辑:AST 扫描 api/**/*.py;注入 from app.core.errors import ...;运行后需人工检查 _require_user 等 helper。 """ from __future__ import annotations import ast import sys from pathlib import Path ROOT = Path(__file__).resolve().parents[1] / "app" TARGETS = [ ROOT / "core" / "decorators.py", *sorted(ROOT.glob("api/**/*.py")), ] IMPORT_LINE = ( "from app.core.errors import AppError, ValidationError, UnauthorizedError, " "ForbiddenError, NotFoundError, ConflictError, ServiceUnavailableError, raise_for_status" ) STATUS_TO_EXCEPTION = { 401: "UnauthorizedError", 403: "ForbiddenError", 404: "NotFoundError", 409: "ConflictError", 503: "ServiceUnavailableError", } def _extract_message(node: ast.AST) -> str | None: if isinstance(node, ast.Constant) and isinstance(node.value, str): return node.value if isinstance(node, ast.JoinedStr): parts = [] for value in node.values: if isinstance(value, ast.Constant) and isinstance(value.value, str): parts.append(value.value) else: return None return "".join(parts) return None def _segment(source: str, node: ast.AST) -> str: return ast.get_source_segment(source, node) or "" def _build_raise(source: str, node: ast.Return, indent: str) -> str | None: if not isinstance(node.value, ast.Tuple) or len(node.value.elts) != 2: return None call, status_node = node.value.elts if not isinstance(call, ast.Call): return None func = call.func if not (isinstance(func, ast.Name) and func.id == "jsonify"): return None if len(call.args) != 1 or call.keywords: return None payload = call.args[0] if not isinstance(payload, ast.Dict): return None error_node = None extras: list[tuple[str, ast.AST]] = [] for key, value in zip(payload.keys, payload.values): if key is None or value is None: return None if isinstance(key, ast.Constant) and key.value == "error": error_node = value else: key_name = key.value if isinstance(key, ast.Constant) else _segment(source, key) extras.append((str(key_name), value)) if error_node is None: return None message = _extract_message(error_node) message_expr = repr(message) if message is not None else _segment(source, error_node).strip() if isinstance(status_node, ast.Constant) and isinstance(status_node.value, int): status = status_node.value status_expr = str(status) else: status = None status_expr = _segment(source, status_node).strip() if extras: detail_items = [f"{key!r}: {_segment(source, value).strip()}" for key, value in extras] details_expr = "{" + ", ".join(detail_items) + "}" if status == 409: return f"{indent}raise ConflictError({message_expr}, details={details_expr})" if status is not None: return ( f"{indent}raise AppError(code='SYSTEM.HTTP_ERROR', message={message_expr}, " f"http_status={status}, details={details_expr})" ) return ( f"{indent}raise AppError(code='SYSTEM.HTTP_ERROR', message={message_expr}, " f"http_status={status_expr}, details={details_expr})" ) if status is not None: cls = STATUS_TO_EXCEPTION.get(status) if cls: return f"{indent}raise {cls}({message_expr})" if status == 400: return f"{indent}raise ValidationError({message_expr})" if status >= 500: return f"{indent}raise AppError(code='SYSTEM.INTERNAL_ERROR', message={message_expr}, http_status={status})" return f"{indent}raise_for_status({message_expr}, {status})" return f"{indent}raise_for_status({message_expr}, {status_expr})" class ErrorMigrator(ast.NodeTransformer): def __init__(self, source: str): self.source = source self.changed = 0 def visit_Return(self, node: ast.Return): indent = " " * (node.col_offset or 0) new = _build_raise(self.source, node, indent) if not new: return node self.changed += 1 wrapped = f"def _migrate():\n{new}\n" return ast.parse(wrapped).body[0].body[0] def _fix_require_user(source: str) -> str: old = ( "def _require_user():\n" " user = get_current_user()\n" " if not user:\n" " return None, (jsonify({'error': 'Unauthorized'}), 401)\n" " return user, None\n" ) new = ( "def _require_user():\n" " user = get_current_user()\n" " if not user:\n" " raise UnauthorizedError()\n" " return user\n" ) source = source.replace(old, new) source = source.replace( " user, err = _require_user()\n if err:\n return err\n", " user = _require_user()\n", ) source = source.replace( " current_user, err = _require_user()\n if err:\n return err\n", " current_user = _require_user()\n", ) return source def _ensure_import(source: str) -> str: if IMPORT_LINE in source: return source lines = source.splitlines(keepends=True) insert_at = 0 for i, line in enumerate(lines): if line.startswith("from ") or line.startswith("import "): insert_at = i + 1 lines.insert(insert_at, IMPORT_LINE + "\n") return "".join(lines) def migrate_file(path: Path) -> int: source = path.read_text(encoding="utf-8") try: tree = ast.parse(source) except SyntaxError as exc: print(f"skip {path}: {exc}", file=sys.stderr) return 0 migrator = ErrorMigrator(source) new_tree = migrator.visit(tree) ast.fix_missing_locations(new_tree) if migrator.changed == 0: return 0 new_source = ast.unparse(new_tree) new_source = _fix_require_user(new_source) new_source = _ensure_import(new_source) path.write_text(new_source, encoding="utf-8") return migrator.changed def main() -> None: total = 0 for path in TARGETS: if not path.exists(): continue count = migrate_file(path) if count: print(f"{path.name}: {count}") total += count print(f"done: {total}") if __name__ == "__main__": main()