config.py 1.07 KB
import os
import configparser

_config = None

BASE_DIR = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
CONFIG_PATH = os.path.join(BASE_DIR, 'config.ini')
DOT_ENV_PATH = os.path.join(BASE_DIR, '.env')


def _load_dot_env():
    if not os.path.exists(DOT_ENV_PATH):
        return
    with open(DOT_ENV_PATH, 'r', encoding='utf-8') as f:
        for line in f:
            line = line.strip()
            if not line or line.startswith('#'):
                continue
            if '=' not in line:
                continue
            key, _, value = line.partition('=')
            key = key.strip()
            value = value.strip().strip('"').strip("'")
            if key and key not in os.environ:
                os.environ[key] = value


def get_config():
    global _config
    if _config is None:
        _load_dot_env()
        _config = configparser.ConfigParser()
        _config.read(CONFIG_PATH, encoding='utf-8')
    return _config


def get_env(key, default=None):
    return os.environ.get(key, default)


def get_project_root():
    return BASE_DIR