Voici un exemple minimal de comment charger et stocker un modèle Pydantic dans un fichier YAML.
Ce code inclut de la logique pour sélectionner le premier chemin qui est inscriptible, ce qui rend facile son utilisation par ex. à la fois dans un conteneur et pour le développement local
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()Une fois modifié, vous pouvez le sauvegarder en utilisant
pydantic_yaml_save.py
global_settings.save_to_first_writable_path()Si cet article vous a aidé, pensez à m'offrir un café ou à faire un don via PayPal pour soutenir la recherche et la publication de nouveaux articles sur TechOverflow