scheme.py 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. import os
  2. import uuid
  3. import json
  4. from datetime import date, datetime
  5. from typing import Optional, Dict, Any, List
  6. from pydantic import BaseModel, field_validator
  7. # --- Pydantic 数据模型 ---
  8. class ImageRecordResponse(BaseModel):
  9. """用于API响应的数据模型,确保数据结构一致"""
  10. img_id: int
  11. img_name: Optional[str] = None
  12. img_path: str
  13. img_result_json: Dict[str, Any] # 这个字段在响应中代表的是 img_result_json_new 或 img_result_json 的实际值
  14. created_at: datetime
  15. @field_validator('img_result_json', mode='before')
  16. @classmethod
  17. def parse_json_string(cls, v):
  18. """
  19. 这个验证器会在Pydantic进行类型检查之前运行 (因为 pre=True)。
  20. 它负责将从数据库取出的JSON字符串转换为Python字典。
  21. """
  22. if isinstance(v, str):
  23. try:
  24. return json.loads(v)
  25. except json.JSONDecodeError:
  26. # 如果数据库中的JSON格式错误,则抛出异常
  27. raise ValueError("Invalid JSON string in database")
  28. return v
  29. def map_row_to_model(row: tuple, columns: List[str]) -> ImageRecordResponse:
  30. """
  31. 将数据库查询出的一行数据映射到Pydantic模型。
  32. 优先使用 img_result_json_new,如果它为 NULL,则使用 img_result_json。
  33. """
  34. row_dict = dict(zip(columns, row))
  35. # Pydantic 字段名为 img_result_json
  36. if 'img_result_json_new' in row_dict and row_dict['img_result_json_new'] is not None:
  37. row_dict['img_result_json'] = row_dict['img_result_json_new']
  38. # 移除 img_result_json_new 字段,因为它不属于 ImageRecordResponse 模型
  39. if 'img_result_json_new' in row_dict:
  40. del row_dict['img_result_json_new']
  41. return ImageRecordResponse(**row_dict)