Skip to content

Instantly share code, notes, and snippets.

@pydanny pydanny/settings.py
Last active Dec 28, 2015

Embed
What would you like to do?
""" For use with something like the following
{ \\ secrets.json
"SECRET_KEY": "I've got a secret!",
"DATABASES_HOST": "127.0.0.1",
"PORT": "5432"
}
"""
# In settings/base.py
from collections import namedtuple
import json
import os
# Ye Typicale Aulde PROJECT ROOT
BASE_DIR = os.path.dirname(os.path.dirname(__file__))
# Normally you should not import ANYTHING from Django directly
# into your settings, but ImproperlyConfigured is an exception.
from django.core.exceptions import ImproperlyConfigured
# JSON-based secrets module
with open(os.path.join(BASE_DIR, "secrets.json")) as f:
data = json.loads(f.read())
# Use namedtuple so secrets becomes a static object.
# secrets is a static object so we don't risk corruption of secret data.
SecretsNamedTuple = namedtuple('SecretsNamedTuple',
data.keys(),
verbose=False)
secrets = SecretsNamedTuple(*[data[x] for x in data.keys()])
def get_secret(setting, secrets=secrets):
""" Get the secret variable or return explicit exception """
try:
return getattr(secrets, setting)
except KeyError:
error_msg = "Set the {0} environment variable".format(setting)
raise ImproperlyConfigured(error_msg)
SECRET_KEY = get_secret("SECRET_KEY")
# Alternative get_secret_as_partial() function using functools.partial
# Possibly overkill and could confuse developers
from functools import partial
def get_secret_as_partial(setting, secrets):
""" Get the secret variable or return explicit exception """
try:
return getattr(secrets, setting)
except KeyError:
error_msg = "Set the {0} environment variable".format(setting)
raise ImproperlyConfigured(error_msg)
get_secret_as_partial = partial(get_secret_as_partial, secrets=secrets)
SECRET_KEY = get_secret_as_partial("SECRET_KEY")
@GrahamDumpleton

This comment has been minimized.

Copy link

commented Nov 20, 2013

Should use absolute paths for location of secrets.json, calculated relative to os.path.dirname(file) as necessary. Will otherwise ponder what you are doing and comment further later.

@pydanny

This comment has been minimized.

Copy link
Owner Author

commented Nov 21, 2013

Okay @GrahamDumpleton, did as you asked and added a BASE_DIR

Also, at https://gist.github.com/pydanny/7567420#file-settings-py-L43-L56 I changed demonstrate use of a partial. FWIW, this might be overkill.

Overall I like this get_secret approach because it allows Apache users and developers in shop that don't allow environment variables to pretty easily use same or similar patterns as we prescribe throughout the rest of the book.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.