django-constance/constance/base.py

49 lines
1.6 KiB
Python
Raw Normal View History

from . import settings
from . import utils
import importlib
2010-08-23 11:06:52 +00:00
2013-04-12 15:39:10 +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)
class Config:
2024-07-05 14:38:26 +00:00
"""The global config wrapper that handles the backend."""
2010-08-23 11:06:52 +00:00
def __init__(self):
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:
config_value = settings.CONFIG[key]
if len(config_value) not in (2, 3):
raise AttributeError(key)
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
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)
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
return result
2010-08-23 11:06:52 +00:00
def __setattr__(self, key, value):
if key not in settings.CONFIG:
2010-08-25 12:55:01 +00:00
raise AttributeError(key)
if len(settings.CONFIG[key]) == 3 and settings.CONFIG[key][2] == 'derived_value':
raise AttributeError(key)
self._backend.set(key, value)
2010-08-23 11:06:52 +00:00
def __dir__(self):
2011-08-29 13:31:44 +00:00
return settings.CONFIG.keys()