import os import uuid import json from datetime import date, datetime from typing import Optional, Dict, Any, List from pydantic import BaseModel, field_validator # --- Pydantic 数据模型 --- class ImageRecordResponse(BaseModel): """用于API响应的数据模型,确保数据结构一致""" img_id: int img_name: Optional[str] = None img_path: str img_result_json: Dict[str, Any] # 这个字段在响应中代表的是 img_result_json_new 或 img_result_json 的实际值 created_at: datetime @field_validator('img_result_json', mode='before') @classmethod def parse_json_string(cls, v): """ 这个验证器会在Pydantic进行类型检查之前运行 (因为 pre=True)。 它负责将从数据库取出的JSON字符串转换为Python字典。 """ if isinstance(v, str): try: return json.loads(v) except json.JSONDecodeError: # 如果数据库中的JSON格式错误,则抛出异常 raise ValueError("Invalid JSON string in database") return v def map_row_to_model(row: tuple, columns: List[str]) -> ImageRecordResponse: """ 将数据库查询出的一行数据映射到Pydantic模型。 优先使用 img_result_json_new,如果它为 NULL,则使用 img_result_json。 """ row_dict = dict(zip(columns, row)) # Pydantic 字段名为 img_result_json if 'img_result_json_new' in row_dict and row_dict['img_result_json_new'] is not None: row_dict['img_result_json'] = row_dict['img_result_json_new'] # 移除 img_result_json_new 字段,因为它不属于 ImageRecordResponse 模型 if 'img_result_json_new' in row_dict: del row_dict['img_result_json_new'] return ImageRecordResponse(**row_dict)