| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768 |
- import json
- from pydantic import BaseModel, model_validator
- from typing import Optional, Any
- from datetime import datetime
- class ConfigurationBase(BaseModel):
- config_key: Optional[str] = None
- config_value: Optional[str] = None
- description: Optional[str] = None
- type: Optional[str] = None
- class ConfigurationCreate(ConfigurationBase):
- config_key: str
- config_value: str
- class ConfigurationUpdate(ConfigurationBase):
- config_value: Optional[str] = None
- description: Optional[str] = None
- type: Optional[str] = None
- class ConfigurationOut(ConfigurationBase):
- id: int
- # 关键点 1: 必须覆盖 config_value 的类型注解为 Any,
- # 否则 Pydantic 会在输出时强行把它转换回字符串,或者报错
- config_value: Any
-
- model_config = {
- "from_attributes": True
- }
- @model_validator(mode='after')
- def parse_config_value_by_type(self) -> 'ConfigurationOut':
- """
- 根据 type 字段自动转换 config_value 的类型
- """
- if self.config_value is None or self.type is None:
- return self
- # 获取原始字符串值
- raw_value = str(self.config_value)
- target_type = self.type.lower()
- try:
- if target_type == 'int' or target_type == 'integer':
- self.config_value = int(raw_value)
-
- elif target_type == 'float':
- self.config_value = float(raw_value)
-
- elif target_type == 'bool' or target_type == 'boolean':
- # 处理 "true", "1", "yes" 等情况
- self.config_value = raw_value.lower() in ('true', '1', 'yes', 'on')
-
- elif target_type in ('json', 'list', 'dict', 'array', 'object'):
- # 尝试解析 JSON
- self.config_value = json.loads(raw_value)
-
- # 如果是 string 或其他未定义类型,保持原样
- except (ValueError, json.JSONDecodeError):
- # 如果转换失败(比如类型是 int 但值是 "abc"),
- # 这里选择保持原始字符串不报错,或者你可以选择抛出错误
- pass
- return self
|