Created
June 22, 2018 15:08
-
-
Save traverseda/7d714a677eabe564c0c13c7a76455d4d to your computer and use it in GitHub Desktop.
12factor/django snippet for configging django via enviroment variables
This file contains hidden or 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
import environ | |
root = environ.Path(__file__) - 2 | |
# SECURITY WARNING: don't run with debug turned on in production! | |
env = environ.Env(DEBUG=(bool, True),) # set default values and casting | |
environ.Env.read_env() # reading .env file | |
ALLOWED_HOSTS = ['localhost', *env("ALLOWED_HOSTS", default="").split(",")] | |
SITE_ROOT = root() | |
DEBUG = env('DEBUG') # False if not in os.environ | |
TEMPLATE_DEBUG = DEBUG | |
DATABASES = { | |
'default': env.db(default="sqlite:///"+root("db.sqlite3")), | |
} | |
public_root = root.path('public/') | |
MEDIA_ROOT = public_root('media') | |
MEDIA_URL = '/media/' | |
STATIC_ROOT = public_root('static') | |
STATIC_URL = '/static/' | |
CACHES = { | |
'default': env.cache(default="pymemcache://"), | |
} | |
# SECURITY WARNING: keep the secret key used in production secret! | |
SECRET_KEY = env('SECRET_KEY',default=None) | |
if not SECRET_KEY: | |
SECRET_FILE = root('secret.txt') | |
try: | |
SECRET_KEY = open(SECRET_FILE).read().strip() | |
except IOError: | |
import random | |
SECRET_KEY = ''.join([random.SystemRandom().choice('abcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*(-_=+)') for i in range(50)]) | |
try: | |
secret = open(SECRET_FILE, 'w') | |
secret.write(SECRET_KEY) | |
secret.close() | |
except IOError: | |
print("Can not store secret key file, using ephemeral secret key, which will cause session errors") | |
print("Please either specify a `SECRET_KEY` in your env, or ensure `{}` if writeable.".format(SECRET_FILE)) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment