Pydantic: Modeli YAML dosyasına yükleme ve kaydetme (minimal örnek)

İşte bir Pydantic modelini YAML dosyasına yükleme ve kaydetmenin minimal bir örneği.

Bu kod, yazılabilir ilk yolu seçen mantığı içerir; bu da hem konteynerde hem de yerel geliştirmede kullanımı kolaylaştırır.

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)
        # Dosya yoksa, varsayılan değerlere sahip bir Settings örneği döndür
        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()

# Genel ayarlar singleton'ı
global_settings = MySettings.from_yaml()

Değiştiğinde, şunu kullanarak kaydedebilirsiniz

pydantic_yaml_save.py
global_settings.save_to_first_writable_path()

Check out similar posts by category: Pydantic Python