Skip to content

Instantly share code, notes, and snippets.

@aubricus
Last active March 8, 2017 01:21
Show Gist options
  • Save aubricus/33d3b9e75a176d5a65a57f8f7731143f to your computer and use it in GitHub Desktop.
Save aubricus/33d3b9e75a176d5a65a57f8f7731143f to your computer and use it in GitHub Desktop.
"""Collect settings for this app from django settings."""
from django.core.exceptions import ImproperlyConfigured
class NotSetButRequired(object):
def __repr__(self):
return '<{0}>'.format(self.__class__.__name__)
NOT_SET_BUT_REQUIRED = NotSetButRequired()
SETTINGS = {
"FOO": NOT_SET_BUT_REQUIRED,
"BAR": "qux.baz",
}
def get_setting(setting_name):
from django.conf import settings
SETTINGS_USER = getattr(settings, "FOOBAR_SETTINGS", {})
SETTING_NAME = setting_name.upper()
SETTINGS.update(SETTINGS_USER)
try:
value = SETTINGS[SETTING_NAME]
if value is NOT_SET_BUT_REQUIRED:
error_msg = "FOOBAR_SETTINGS['{}'] is a required setting but is unset".format(SETTING_NAME)
raise ImproperlyConfigured(error_msg)
else:
return value
except KeyError:
raise KeyError("Got unsupported settings key {}".format(SETTING_NAME))
except Exception:
print("Caught unhandled exception while accessing FOOBAR_SETTINGS")
raise
# ... Other django settings above
FOOBAR_SETTINGS = {
"FOO": "http://example.com",
"BAR": "animals.kittens",
}
# How to override ...
FOOBAR_SETTINGS.update({
"FOO": "http://google.com",
})
@aubricus
Copy link
Author

aubricus commented Mar 8, 2017

Just a quick gist based on some generic django app settings:

  • Explicitly declare / handle settings access
  • Settings, if they are required, and their default values are self-documenting
  • Provide simple api to get settings from django.conf.settings: get_setting
  • Simplify setting access by allowing lowercase setting keys
  • Raise a useful error if a setting is required but not configured
  • Raise a useful error if a setting is not supported
  • Provide setting namespace FOOBAR_SETTINGS

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment