import os from types import MappingProxyType from dotenv import dotenv_values PROJECT_ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Dict to hold values from dotenv files; keys are filenames, values are dictionaries of env vars _dotenv_values = {} def get_cfg(env='qa', force_refresh=False): environment_name = os.getenv('ENV_NAME', env) dotenv_path = os.path.join(PROJECT_ROOT, f'.env.{environment_name}') if not os.path.exists(dotenv_path): raise FileNotFoundError(f"{dotenv_path} does not exist") if dotenv_path not in _dotenv_values or force_refresh: # Load the env vars from the dotenv file and store them in the _dotenv_values dict _dotenv_values[dotenv_path] = dotenv_values(dotenv_path) # Now, we're sure that _dotenv_values[dotenv_path] contains up-to-date env vars from dotenv_path dotenv_vars = _dotenv_values[dotenv_path] config_dict = { 'client_id': dotenv_vars.get('CLIENT_ID'), 'client_secret': dotenv_vars.get('CLIENT_SECRET'), 'token_url': dotenv_vars.get('TOKEN_FETCH_URL'), 'login': dotenv_vars.get('LOGIN'), 'password': dotenv_vars.get('PASSWORD'), 'audience': dotenv_vars.get('AUDIENCE'), 'scopes': dotenv_vars.get('SCOPES', '').split(','), 'api_url': dotenv_vars.get('API_URL') } config = MappingProxyType(config_dict) # immutable dict return config