Add Config class
This commit is contained in:
51
motor_passo/config.py
Normal file
51
motor_passo/config.py
Normal file
@@ -0,0 +1,51 @@
|
||||
import json
|
||||
import logging
|
||||
|
||||
from dataclasses import dataclass, field
|
||||
from motor_passo import config_dir
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
@dataclass
|
||||
class Config:
|
||||
config_path: Path
|
||||
|
||||
_json: dict = field(default_factory=dict)
|
||||
_l: logging.Logger = None
|
||||
|
||||
def __post_init__(self):
|
||||
self._l = logging.getLogger(__name__).getChild(self.__class__.__name__)
|
||||
|
||||
def load(self) -> bool:
|
||||
self.config_path = self.config_path.expanduser()
|
||||
|
||||
self._l.info(f"Carregando configuração de {self.config_path}")
|
||||
|
||||
try:
|
||||
with self.config_path.open("r") as f:
|
||||
self._json = json.load(f)
|
||||
|
||||
for k, v in self._json.items():
|
||||
setattr(self, k, v)
|
||||
except FileNotFoundError:
|
||||
self._l.exception("Arquivo de configuração não existe")
|
||||
raise RuntimeError() # TODO: Usar exception customizada
|
||||
except json.JSONDecodeError:
|
||||
self._l.exception("Configuração inválida")
|
||||
raise RuntimeError() # TODO: Usar exception customizada
|
||||
|
||||
return True
|
||||
|
||||
|
||||
_configs = {}
|
||||
|
||||
|
||||
def get_config(name: str) -> Config:
|
||||
global _configs
|
||||
|
||||
if name in _configs:
|
||||
return _configs[name]
|
||||
|
||||
_configs[name] = Config(config_path=config_dir / name)
|
||||
_configs[name].load()
|
||||
return _configs[name]
|
||||
Reference in New Issue
Block a user