history.py 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. from pydantic import BaseModel
  2. from typing import Optional
  3. from datetime import datetime
  4. from enum import Enum
  5. class GameTypeEnum(str, Enum):
  6. """题目类型枚举,限制为A-E"""
  7. TYPE_A = "A"
  8. TYPE_B = "B"
  9. TYPE_C = "C"
  10. TYPE_D = "D"
  11. TYPE_E = "E"
  12. class History(BaseModel):
  13. """历史记录数据模型
  14. 用于规范历史记录的数据结构,确保数据的一致性和有效性
  15. """
  16. id: Optional[int] = None
  17. game_type: GameTypeEnum
  18. question: str
  19. numbers: str
  20. answers: str
  21. created_at: Optional[datetime] = None
  22. class Config:
  23. json_encoders = {
  24. datetime: lambda v: v.isoformat()
  25. }
  26. @classmethod
  27. def from_db_record(cls, record: dict):
  28. """从数据库记录创建模型对象"""
  29. return cls(**record)
  30. def to_db_record(self):
  31. """转换为数据库记录格式"""
  32. record = self.model_dump(exclude={'id', 'created_at'} if self.id is None else {'created_at'})
  33. # 确保game_type是字符串值
  34. if isinstance(record['game_type'], GameTypeEnum):
  35. record['game_type'] = record['game_type'].value
  36. return record