Код: Выделить всё
- entry1:
attribute: "Test1"
amount: 1
price: 123.45
- entry2:
attribute: "Test1"
amount: 10
price: 56.78
< /code>
Для этой структуры данных я создал три вложенные модели следующим образом: < /p>
# Models
class EntryValues(BaseModel):
attribute: str
amount: int
price: float
class Entry(BaseModel):
entry1: EntryValues
entry2: EntryValues
class Config(BaseModel):
__root__: list[Entry]
< /code>
Мой код для чтения файла конфигурации Yaml выглядит следующим образом: < /p>
# get YAML config path
def get_cfg_path() -> Path:
return CWD
# read YAML file
def read_cfg(file_name: str, file_path: Path = None) -> YAML:
if not file_path:
file_path = get_cfg_path()
if file_path:
try:
file = open(file_path / file_name, "r")
except Exception as e:
print(f"open file {file_name} failed", e)
sys.exit(1)
else:
return load(file.read())
else:
raise Exception(f"Config file {file_name} not found!")
< /code>
Теперь я хочу распаковать значения YAML до моей модели. Для этого я попытался распаковать значения с помощью оператора **
Код: Выделить всё
# Unpack and create config file
def create_cfg(file_name: str = None) -> Config:
config_file = read_cfg(file_name=file_name)
_config = Config(**config_file.data)
return _config
< /code>
Я был бы признателен любой помощью. Бит без использования файла YAML. Я не совсем понимаю, почему следующее бросает валидацию
Рассмотрим следующий список записей (это та же структура данных, которую я бы получил из моего файла YAML):
Код: Выделить всё
entries = [
{'entry1': {'attribute': 'Test1', 'amount': 1, 'price': 123.45}},
{'entry2': {'attribute': 'Test2', 'amount': 10, 'price': 56.78}}
]
Код: Выделить всё
for entry in entries:
Entry(**entry)
< /code>
ошибка: < /p>
ValidationError: 1 validation error for Entry
entry2
field required (type=value_error.missing)
< /code>
Однако, если список содержит только один словарь записи, то он работает: < /p>
class Entry(BaseModel):
entry1: EntryValues
#entry2: EntryValues
entries = [
{'entry1': {'attribute': 'Test1', 'amount': 1, 'price': 123.45}}
]
for entry in entries:
Entry(**entry)
Подробнее здесь: https://stackoverflow.com/questions/729 ... ation-file