#!/usr/bin/env python import os import sys if __name__ == "__main__": os.environ.setdefault("DJANGO_SETTINGS_MODULE", "project.settings") from django.core.management import execute_from_command_line execute_from_command_line(sys.argv)
import os
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "project.settings")
from django.core.wsgi import get_wsgi_application
application = get_wsgi_application()
project/settings.py
DEBUG = False
SECRET_KEY = 'change-me'
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': 'mydatabase',
}
}
try:
from local_settings import *
except ImportError:
pass
project/local_settings.py
DEBUG = True
SECRET_KEY = 'my-secret-key'
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': 'mydatabase',
}
}
project/local_settings.py
INSTALLED_APPS += ('debug_toolbar.apps.DebugToolbarConfig', ) # error
MIDDLEWARE_CLASSES += (
'django.contrib.sessions.middleware.SessionMiddleware',
) # error
Apps sometimes store config as constants in the code.
This is a violation of twelve-factor, which requires strict separation of config from code.
Config varies substantially across deploys, code does not.
project/settings/local.py
from .base import *
INSTALLED_APPS += ('debug_toolbar.apps.DebugToolbarConfig', )
MIDDLEWARE_CLASSES += (
'debug_toolbar.middleware.DebugToolbarMiddleware',
)
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "project.settings.development)
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "project.settings.production")
python manage.py tests --settings=project.settings.tests
# project/settings/base.py
import os
DEBUG = bool(os.environ.get('DEBUG', False))
SECRET_KEY = os.environ['SECRET_KEY']
ALLOWED_HOSTS = os.environ['ALLOWED_HOSTS'].split()
# project/settings/base.py
import os
from django.core.exceptions import ImproperlyConfigured
NOTSET = object()
def get_env_setting(setting, default=NOTSET):
try:
return os.environ[setting]
except KeyError:
if default is NOTSET:
raise ImproperlyConfigured("Set the %s env variable" % setting)
return default
DEBUG = bool(get_env_setting('DEBUG', Fals))
SECRET_KEY = get_env_setting('SECRET_KEY')
ALLOWED_HOSTS = get_env_setting('ALLOWED_HOSTS').split()
import environ
env = environ.Env()
DEBUG = env.bool('DEBUG', default=False)
# or
env = environ.Env(DEBUG=(bool, False),)
DEBUG = env('DEBUG')
import environ
env = environ.Env()
# Raises ImproperlyConfigured exception if SITE_ID is not defined in os.environ or if os.environ['SITE_ID'] contains not valid int.
SITE_ID = env.int('SITE_ID')
# Raises ImproperlyConfigured exception if SECRET_KEY not in os.environ
SECRET_KEY = env('SECRET_KEY')
import environ
env = environ.Env()
DATABASES = {
# Raises ImproperlyConfigured if DATABASE_URL not in os.environ
'default': env.db(default='sqlite:////tmp/my-tmp-sqlite.db'),
}
export DEBUG=1
export SECRET_KEY=secure
[program:my-project]
environment=DEBUG="1",SECRET_KEY="secure"
[uwsgi]
env=DEBUG=1
env=SECRET_KEY=secure