Pydantic:如何在 YAML 文件中加载和存储模型(最小示例)
以下是如何在 YAML 文件中加载和存储 Pydantic 模型的最小示例。
此代码包含选择第一个可写路径的逻辑,这使得它易于在容器和本地开发中使用
pydantic_yaml_example.py
from pydantic import BaseModel, ValidationError, Field
import yaml
import os
class MySettings(BaseModel):
variable1: float = Field(default=1.5, help="TODO enter your description here")
variable2: str = Field(default="foobar", help="TODO enter your description here")
_default_paths = ['/data/settings.yaml', './settings.yaml']
@classmethod
def from_yaml(cls) -> 'MySettings':
for path in cls._default_paths.default:
if os.path.exists(path):
with open(path, 'r', encoding="utf-8") as f:
data = yaml.safe_load(f)
return cls(**data)
# If no files exist, return a Settings instance with default values
print(f"None of the settings files found in {cls._default_paths}. Initializing with default values.")
_settings = cls()
_settings.save_to_first_writable_path()
return _settings
def save_to_first_writable_path(self) -> None:
for path in self._default_paths:
try:
with open(path, 'w', encoding="utf-8") as f:
yaml.safe_dump(self.model_dump(), f)
print(f"Settings saved to {path}")
return
except IOError:
print(f"Unable to write to {path}")
raise IOError(f"None of the paths in {self._default_paths} are writable.")
def to_yaml(self) -> None:
self.save_to_first_writable_path()
# Global settings singleton
global_settings = MySettings.from_yaml()更改后,你可以使用以下命令保存
pydantic_yaml_save.py
global_settings.save_to_first_writable_path()If this post helped you, please consider buying me a coffee or donating via PayPal to support research & publishing of new posts on TechOverflow