读取conf时修正不对的Literal类型
All checks were successful
ci/woodpecker/push/check_format Pipeline was successful
All checks were successful
ci/woodpecker/push/check_format Pipeline was successful
This commit is contained in:
parent
b27187cc57
commit
28243b0e1f
1 changed files with 25 additions and 1 deletions
|
@ -1,4 +1,4 @@
|
||||||
from typing import Literal
|
from typing import Literal, get_args, get_origin
|
||||||
|
|
||||||
from pydantic import BaseModel, model_validator
|
from pydantic import BaseModel, model_validator
|
||||||
from pydantic_core import PydanticUndefined
|
from pydantic_core import PydanticUndefined
|
||||||
|
@ -14,6 +14,30 @@ class ConfModel(BaseModel):
|
||||||
data[name] = field.annotation()
|
data[name] = field.annotation()
|
||||||
else:
|
else:
|
||||||
data[name] = field.default
|
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
|
return data
|
||||||
|
|
||||||
|
|
||||||
|
|
Loading…
Add table
Add a link
Reference in a new issue