96 lines
2.2 KiB
Python
96 lines
2.2 KiB
Python
import os
|
|
import configparser
|
|
from pathlib import Path
|
|
|
|
_APP_INI_FILE = Path(__file__).resolve().parent.parent / "app.ini"
|
|
_config = None
|
|
|
|
|
|
def _load_config():
|
|
global _config
|
|
if _config is not None:
|
|
return _config
|
|
_config = configparser.ConfigParser()
|
|
if _APP_INI_FILE.exists():
|
|
_config.read(str(_APP_INI_FILE), encoding="utf-8")
|
|
return _config
|
|
|
|
|
|
def get(section, key, fallback=None):
|
|
cfg = _load_config()
|
|
env_key = f"APP_{section.upper()}_{key.upper()}"
|
|
env_val = os.environ.get(env_key)
|
|
if env_val is not None:
|
|
return env_val
|
|
return cfg.get(section, key, fallback=fallback)
|
|
|
|
|
|
def getint(section, key, fallback=0):
|
|
val = get(section, key, fallback=None)
|
|
if val is None:
|
|
return fallback
|
|
try:
|
|
return int(val)
|
|
except (ValueError, TypeError):
|
|
return fallback
|
|
|
|
|
|
def getfloat(section, key, fallback=0.0):
|
|
val = get(section, key, fallback=None)
|
|
if val is None:
|
|
return fallback
|
|
try:
|
|
return float(val)
|
|
except (ValueError, TypeError):
|
|
return fallback
|
|
|
|
|
|
def getboolean(section, key, fallback=False):
|
|
val = get(section, key, fallback=None)
|
|
if val is None:
|
|
return fallback
|
|
return val.lower() in ("true", "1", "yes", "on")
|
|
|
|
|
|
def getlist(section, key, fallback=None, separator=","):
|
|
val = get(section, key, fallback=None)
|
|
if val is None:
|
|
return fallback if fallback is not None else []
|
|
return [item.strip() for item in val.split(separator) if item.strip()]
|
|
|
|
|
|
def getdict(section, key, fallback=None, entry_sep=",", kv_sep="="):
|
|
val = get(section, key, fallback=None)
|
|
if val is None:
|
|
return fallback if fallback is not None else {}
|
|
result = {}
|
|
for entry in val.split(entry_sep):
|
|
entry = entry.strip()
|
|
if kv_sep in entry:
|
|
k, v = entry.split(kv_sep, 1)
|
|
result[k.strip()] = v.strip()
|
|
return result
|
|
|
|
|
|
def sections():
|
|
cfg = _load_config()
|
|
return cfg.sections()
|
|
|
|
|
|
def has_section(section):
|
|
cfg = _load_config()
|
|
return cfg.has_section(section)
|
|
|
|
|
|
def items(section):
|
|
cfg = _load_config()
|
|
if cfg.has_section(section):
|
|
return cfg.items(section)
|
|
return []
|
|
|
|
|
|
def reload():
|
|
global _config
|
|
_config = None
|
|
_load_config()
|