2024-07-03 14:21:33 +00:00
|
|
|
from . import settings
|
|
|
|
|
from . import utils
|
2025-03-05 15:26:14 +00:00
|
|
|
import importlib
|
2010-08-23 11:06:52 +00:00
|
|
|
|
2013-04-12 15:39:10 +00:00
|
|
|
|
2025-03-05 15:26:14 +00:00
|
|
|
def get_function_from_string(path):
|
|
|
|
|
module_path, function_name = path.rsplit('.', 1)
|
|
|
|
|
module = importlib.import_module(module_path)
|
|
|
|
|
return getattr(module, function_name)
|
|
|
|
|
|
2019-12-23 21:20:41 +00:00
|
|
|
class Config:
|
2024-07-05 14:38:26 +00:00
|
|
|
"""The global config wrapper that handles the backend."""
|
2024-07-03 14:21:33 +00:00
|
|
|
|
2010-08-23 11:06:52 +00:00
|
|
|
def __init__(self):
|
2024-07-03 14:21:33 +00:00
|
|
|
super().__setattr__('_backend', utils.import_module_attr(settings.BACKEND)())
|
2010-08-23 11:06:52 +00:00
|
|
|
|
|
|
|
|
def __getattr__(self, key):
|
2010-08-25 12:55:01 +00:00
|
|
|
try:
|
2025-03-05 15:26:14 +00:00
|
|
|
config_value = settings.CONFIG[key]
|
|
|
|
|
if len(config_value) not in (2, 3):
|
2015-06-08 14:13:40 +00:00
|
|
|
raise AttributeError(key)
|
2025-03-05 15:26:14 +00:00
|
|
|
default = config_value[0]
|
|
|
|
|
derived = len(config_value) == 3 and config_value[2] == 'derived_value'
|
2024-07-05 14:38:26 +00:00
|
|
|
except KeyError as e:
|
|
|
|
|
raise AttributeError(key) from e
|
2025-03-05 15:26:14 +00:00
|
|
|
|
|
|
|
|
if derived:
|
|
|
|
|
if isinstance(default, str):
|
|
|
|
|
default = get_function_from_string(default)
|
|
|
|
|
assert callable(default), "derived_value must have a callable default value"
|
|
|
|
|
return default(self)
|
|
|
|
|
|
2010-11-30 23:20:23 +00:00
|
|
|
result = self._backend.get(key)
|
2010-08-23 11:06:52 +00:00
|
|
|
if result is None:
|
|
|
|
|
result = default
|
|
|
|
|
setattr(self, key, default)
|
2010-08-23 13:48:15 +00:00
|
|
|
return result
|
2010-11-30 23:20:23 +00:00
|
|
|
return result
|
2010-08-23 11:06:52 +00:00
|
|
|
|
|
|
|
|
def __setattr__(self, key, value):
|
2010-11-30 23:20:23 +00:00
|
|
|
if key not in settings.CONFIG:
|
2010-08-25 12:55:01 +00:00
|
|
|
raise AttributeError(key)
|
2025-03-05 15:26:14 +00:00
|
|
|
if len(settings.CONFIG[key]) == 3 and settings.CONFIG[key][2] == 'derived_value':
|
|
|
|
|
raise AttributeError(key)
|
2010-11-30 23:20:23 +00:00
|
|
|
self._backend.set(key, value)
|
2010-08-23 11:06:52 +00:00
|
|
|
|
2010-08-23 15:10:44 +00:00
|
|
|
def __dir__(self):
|
2011-08-29 13:31:44 +00:00
|
|
|
return settings.CONFIG.keys()
|