127 lines
3.8 KiB
Python
127 lines
3.8 KiB
Python
#
|
|
# Note the settings file is hardcoded in this class at the top after imports.
|
|
#
|
|
# To make a new settings section, just add the setting dict to your yaml
|
|
# and then define the data class below in the config data classes area.
|
|
#
|
|
# Example use from anywhere - this will always return the same singleton
|
|
# from settings import get_settings
|
|
# def main():
|
|
# settings = get_settings()
|
|
# print(settings.database.host) # Autocomplete works
|
|
# print(settings.logging.level)
|
|
|
|
# if __name__ == "__main__":
|
|
# main()
|
|
|
|
import functools
|
|
from pathlib import Path
|
|
from typing import Any, Callable, TypeVar
|
|
from dataclasses import dataclass, fields, is_dataclass, field, MISSING
|
|
|
|
try:
|
|
import yaml
|
|
except ModuleNotFoundError:
|
|
import logging
|
|
import sys
|
|
|
|
logger = logging.getLogger(__file__)
|
|
msg = (
|
|
"Required modules are not installed. "
|
|
"Can not continue with module / application loading.\n"
|
|
"Install it with: pip install -r requirements"
|
|
)
|
|
print(msg, file=sys.stderr)
|
|
logger.error(msg)
|
|
exit()
|
|
|
|
# ---------- CONFIG DATA CLASSES ----------
|
|
@dataclass
|
|
class DatabaseConfig:
|
|
host: str = "localhost"
|
|
port: int = 5432
|
|
username: str = "root"
|
|
password: str = ""
|
|
|
|
|
|
@dataclass
|
|
class AppConfig:
|
|
name: str = "MyApp"
|
|
version_major: int = 1
|
|
version_minor: int = 0
|
|
production: bool = False
|
|
enabled: bool = True
|
|
token_expiry: int = 3600
|
|
|
|
|
|
@dataclass
|
|
class Settings:
|
|
database: DatabaseConfig = field(default_factory=DatabaseConfig)
|
|
app: AppConfig = field(default_factory=AppConfig)
|
|
|
|
@classmethod
|
|
def from_yaml(cls, path: str | Path) -> "Settings":
|
|
"""Load settings from YAML file into a Settings object."""
|
|
with open(path, "r", encoding="utf-8") as f:
|
|
raw: dict[str, Any] = yaml.safe_load(f) or {}
|
|
|
|
init_kwargs = {}
|
|
for f_def in fields(cls):
|
|
yaml_value = raw.get(f_def.name, None)
|
|
|
|
# Determine default value from default_factory or default
|
|
if f_def.default_factory is not MISSING:
|
|
default_value = f_def.default_factory()
|
|
elif f_def.default is not MISSING:
|
|
default_value = f_def.default
|
|
else:
|
|
default_value = None
|
|
|
|
# Handle nested dataclasses
|
|
if is_dataclass(f_def.type):
|
|
if isinstance(yaml_value, dict):
|
|
# Merge YAML values with defaults
|
|
merged_data = {fld.name: getattr(default_value, fld.name) for fld in fields(f_def.type)}
|
|
merged_data.update(yaml_value)
|
|
init_kwargs[f_def.name] = f_def.type(**merged_data)
|
|
else:
|
|
init_kwargs[f_def.name] = default_value
|
|
else:
|
|
init_kwargs[f_def.name] = yaml_value if yaml_value is not None else default_value
|
|
|
|
return cls(**init_kwargs)
|
|
|
|
|
|
# ---------- SINGLETON DECORATOR ----------
|
|
T = TypeVar("T")
|
|
|
|
def singleton_loader(func: Callable[..., T]) -> Callable[..., T]:
|
|
"""Ensure the function only runs once, returning the cached value."""
|
|
cache: dict[str, T] = {}
|
|
|
|
@functools.wraps(func)
|
|
def wrapper(*args, **kwargs) -> T:
|
|
if func.__name__ not in cache:
|
|
cache[func.__name__] = func(*args, **kwargs)
|
|
return cache[func.__name__]
|
|
|
|
return wrapper
|
|
|
|
|
|
@singleton_loader
|
|
def get_settings(config_path: str | Path | None = None) -> Settings:
|
|
"""
|
|
Returns the singleton Settings instance.
|
|
|
|
Args:
|
|
config_path: Optional path to the YAML config file. If not provided,
|
|
defaults to 'config/settings.yaml' in the current working directory.
|
|
"""
|
|
DEFAULT_SETTINGS_FILE = Path.cwd() / "config" /"settings.yaml"
|
|
|
|
if config_path is None:
|
|
config_path = DEFAULT_SETTINGS_FILE
|
|
else:
|
|
config_path = Path(config_path)
|
|
|
|
return Settings.from_yaml(config_path) |