Add Config class

This commit is contained in:
2023-10-29 20:56:03 -03:00
parent e0422f066b
commit 02051ebda7
4 changed files with 72 additions and 1 deletions

View File

@@ -0,0 +1,7 @@
from appdirs import AppDirs
from pathlib import Path
dirs = AppDirs("spectrometer", appauthor="uff")
log_dir = Path(dirs.user_log_dir) # XXX
config_dir = Path(dirs.user_config_dir) # XXX
data_dir = Path(dirs.user_data_dir)

51
motor_passo/config.py Normal file
View 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]

14
poetry.lock generated
View File

@@ -1,5 +1,17 @@
# This file is automatically @generated by Poetry and should not be changed by hand. # This file is automatically @generated by Poetry and should not be changed by hand.
[[package]]
name = "appdirs"
version = "1.4.4"
description = "A small Python module for determining appropriate platform-specific dirs, e.g. a \"user data dir\"."
category = "main"
optional = false
python-versions = "*"
files = [
{file = "appdirs-1.4.4-py2.py3-none-any.whl", hash = "sha256:a841dacd6b99318a741b166adb07e19ee71a274450e68237b4650ca1055ab128"},
{file = "appdirs-1.4.4.tar.gz", hash = "sha256:7d5d0167b2b1ba821647616af46a749d1c653740dd0d2415100fe26e27afdf41"},
]
[[package]] [[package]]
name = "flake8" name = "flake8"
version = "6.0.0" version = "6.0.0"
@@ -113,4 +125,4 @@ tomli = ">=2.0.1"
[metadata] [metadata]
lock-version = "2.0" lock-version = "2.0"
python-versions = "^3.9" python-versions = "^3.9"
content-hash = "88cff2fd871e1c4248abedb8ef45af99e90ac4ef620fe4ed32fb752b63fc6502" content-hash = "2996806b100690aaf6436bfd564c5c90567d3ec71725e9b177aab422e6ea66b1"

View File

@@ -10,6 +10,7 @@ packages = [{include = "motor_passo"}]
python = "^3.9" python = "^3.9"
rpi-gpio = "^0.7.1" rpi-gpio = "^0.7.1"
paho-mqtt = "^1.6.1" paho-mqtt = "^1.6.1"
appdirs = "^1.4.4"
[tool.poetry.group.dev.dependencies] [tool.poetry.group.dev.dependencies]