Created
December 1, 2023 21:56
-
-
Save marksweb/2a4d4114248a99fc011bded3eeb000bb to your computer and use it in GitHub Desktop.
Using lazy settings in django apps
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# myapp/conf.py | |
from core.settings import Settings | |
DEFAULTS = { | |
'TEMP_DIR': '/tmp/' | |
} | |
settings = Settings(DEFAULTS) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# core/settings.py | |
from django.conf import settings | |
class Settings: | |
""" | |
Lazy settings wrapper, for use in app conf.py files | |
""" | |
def __init__(self, defaults): | |
""" | |
Constructor | |
:param defaults: default values for settings, will be return if | |
not overridden in the project settings | |
:type defaults: dict | |
""" | |
self.defaults = defaults | |
def __getattr__(self, name): | |
""" | |
Return the setting with the specified name, from the project settings | |
(if overridden), else from the default values passed in during | |
construction. | |
:param name: name of the setting to return | |
:type name: str | |
:return: the named setting | |
:raises: AttributeError -- if the named setting is not found | |
""" | |
if hasattr(settings, name): | |
return getattr(settings, name) | |
if name in self.defaults: | |
return self.defaults[name] | |
raise AttributeError("'{name}' setting not found".format(name=name)) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# myapp/views.py | |
from myapp.conf import settings | |
print(settings.DEBUG) | |
print(settings.TEMP_DIR) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment