读取conf时修正不对的Literal类型
All checks were successful
ci/woodpecker/push/check_format Pipeline was successful

This commit is contained in:
Elaina 2024-12-06 22:01:57 +08:00
parent b27187cc57
commit 28243b0e1f

View file

@ -1,4 +1,4 @@
from typing import Literal
from typing import Literal, get_args, get_origin
from pydantic import BaseModel, model_validator
from pydantic_core import PydanticUndefined
@ -14,6 +14,30 @@ class ConfModel(BaseModel):
data[name] = field.annotation()
else:
data[name] = field.default
else:
value = data[name]
expected_type = field.annotation
# 处理嵌套的 BaseModel
if isinstance(field.annotation, type) and issubclass(
field.annotation, BaseModel
):
if not isinstance(value, dict): # 确保嵌套类型为字典
value = {}
# 递归调用嵌套模型的验证器
data[name] = field.annotation(**value)
# 检查 Literal 类型并修正
elif get_origin(expected_type) is Literal:
valid_literals = get_args(expected_type)
if value not in valid_literals:
# 修正为默认值
data[name] = (
field.default
if field.default is not PydanticUndefined
else None
)
return data