From b1534a9ff998922606932f60b97e2873748b9834 Mon Sep 17 00:00:00 2001 From: Klaus-Uwe Mitterer Date: Wed, 30 Dec 2020 10:32:27 +0100 Subject: [PATCH] Add (lazy) DBSettings object inspired by django.conf.settings --- dbsettings/functions.py | 49 ++++++++++++++++++++++++++++++++++++++++- 1 file changed, 48 insertions(+), 1 deletion(-) diff --git a/dbsettings/functions.py b/dbsettings/functions.py index 71c895f..203aa10 100644 --- a/dbsettings/functions.py +++ b/dbsettings/functions.py @@ -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() \ No newline at end of file