60 lines
2 KiB
Python
60 lines
2 KiB
Python
import json
|
|
import os
|
|
import re
|
|
from pathlib import Path
|
|
from types import SimpleNamespace
|
|
|
|
|
|
class Config:
|
|
"""Classe responsável por carregar arquivos JSON e substituir variáveis de ambiente."""
|
|
|
|
@staticmethod
|
|
def _resolve_env_vars(value):
|
|
"""
|
|
Substitui placeholders ${VAR} por valores das variáveis de ambiente.
|
|
Funciona recursivamente para dicionários, listas e strings.
|
|
"""
|
|
if isinstance(value, str):
|
|
# Procura padrões como ${VAR_NAME}
|
|
pattern = re.compile(r"\$\{([^}^{]+)\}")
|
|
matches = pattern.findall(value)
|
|
for var in matches:
|
|
env_value = os.getenv(var)
|
|
if env_value is None:
|
|
raise ValueError(f"Variável de ambiente '{var}' não definida.")
|
|
value = value.replace(f"${{{var}}}", env_value)
|
|
return value
|
|
|
|
elif isinstance(value, dict):
|
|
return {k: Config._resolve_env_vars(v) for k, v in value.items()}
|
|
|
|
elif isinstance(value, list):
|
|
return [Config._resolve_env_vars(v) for v in value]
|
|
|
|
return value
|
|
|
|
@staticmethod
|
|
def get(name: str):
|
|
"""
|
|
Carrega um arquivo JSON de configuração e substitui variáveis de ambiente.
|
|
|
|
Args:
|
|
name (str): Nome do arquivo dentro de /config (ex: "database/mysql.json")
|
|
|
|
Returns:
|
|
SimpleNamespace: Objeto com os valores resolvidos acessíveis via ponto.
|
|
"""
|
|
base_dir = Path(__file__).resolve().parent
|
|
config_path = base_dir.parent.parent / "config" / name
|
|
|
|
# Lê o arquivo JSON
|
|
with open(config_path, "r", encoding="utf-8") as f:
|
|
data = json.load(f)
|
|
|
|
# Substitui variáveis de ambiente
|
|
resolved_data = Config._resolve_env_vars(data)
|
|
|
|
# Retorna como objeto acessível por ponto
|
|
return json.loads(
|
|
json.dumps(resolved_data), object_hook=lambda d: SimpleNamespace(**d)
|
|
)
|