Skip to content

Instantly share code, notes, and snippets.

@marksweb
Created December 1, 2023 21:56
Show Gist options
  • Save marksweb/2a4d4114248a99fc011bded3eeb000bb to your computer and use it in GitHub Desktop.
Save marksweb/2a4d4114248a99fc011bded3eeb000bb to your computer and use it in GitHub Desktop.
Using lazy settings in django apps
# myapp/conf.py
from core.settings import Settings
DEFAULTS = {
'TEMP_DIR': '/tmp/'
}
settings = Settings(DEFAULTS)
# 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))
# 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