Add (lazy) DBSettings object inspired by django.conf.settings

This commit is contained in:
Kumi 2020-12-30 10:32:27 +01:00
parent 6f432e038a
commit b1534a9ff9

View file

@ -1,4 +1,50 @@
from dbsettings.models import Setting
from .models import Setting
from django.utils.functional import LazyObject, empty
class DBSettings:
def __init__(self):
for setting in Setting.objects.all():
if setting.key.isupper():
setattr(self, setting.key, setting.value)
def __setattr__(self, name, value):
setting, _ = Setting.objects.get_or_create(key=name)
setting.value = value
setting.save()
self.__dict__[name] = value
def __delattr__(self, name):
setting = Setting.objects.get(key=name)
setting.delete()
self.__dict__.pop(name, None)
class LazyDBSettings(LazyObject):
def _setup(self):
self._wrapped = DBSettings()
def __getattr__(self, name):
if self._wrapped is empty:
self._setup()
val = getattr(self._wrapped, name)
self.__dict__[name] = val
return val
def __setattr__(self, name, value):
if name == "_wrapped":
self.__dict__.clear()
else:
self.__dict__.pop(name, None)
super().__setattr__(name, value)
def __delattr__(self, name):
super().__delattr__(name)
self.__dict__.pop(name, None)
def getValue(key, default=None):
try:
@ -15,3 +61,4 @@ def setValue(key, value):
obj.save()
return True
dbsettings = LazyDBSettings()