Settings from the Environment
Part of the JSON APIs section of Coddy's Django journey. Lesson 18 of 19.
Once your site is deployed, copied to a server on the internet, three settings must change. DEBUG = True shows your code and every URL pattern to anyone. SECRET_KEY signs sessions, so it cannot sit in code others read. ALLOWED_HOSTS lists the domains the site answers to.
The usual answer: read them from environment variables, values the server gives the program when it starts. os.environ.get(name, default) reads one, and the default is what your own computer gets:
PAGE_SIZE = int(os.environ.get("PAGE_SIZE", "20"))
MAINTENANCE = os.environ.get("MAINTENANCE", "no") == "yes"A variable is always a string, so turn it into the type you need: int() for a number, a comparison for a real boolean, split(",") for a list. Pick safe defaults: a forgotten variable leaves DEBUG off.
Challenge
MediumIn mysite/settings.py, read from the environment:
SECRET_KEYfromDJANGO_SECRET_KEY, default"django-insecure-change-me".DEBUG:Trueonly whenDJANGO_DEBUGis"True".ALLOWED_HOSTSfromDJANGO_ALLOWED_HOSTS, comma-separated, defaultlocalhost,127.0.0.1.
Press Run, then open /nope/: with DEBUG off, the 404 page lists no URL patterns.
Try it yourself
from pathlib import Path
BASE_DIR = Path(__file__).resolve().parent.parent
SECRET_KEY = "django-insecure-change-me"
DEBUG = True
ALLOWED_HOSTS = []
INSTALLED_APPS = [
"django.contrib.admin",
"django.contrib.auth",
"django.contrib.contenttypes",
"django.contrib.sessions",
"django.contrib.messages",
"django.contrib.staticfiles",
"tasks",
]
MIDDLEWARE = [
"django.middleware.security.SecurityMiddleware",
"django.contrib.sessions.middleware.SessionMiddleware",
"django.middleware.common.CommonMiddleware",
"django.middleware.csrf.CsrfViewMiddleware",
"django.contrib.auth.middleware.AuthenticationMiddleware",
"django.contrib.messages.middleware.MessageMiddleware",
"django.middleware.clickjacking.XFrameOptionsMiddleware",
]
ROOT_URLCONF = "mysite.urls"
TEMPLATES = [
{
"BACKEND": "django.template.backends.django.DjangoTemplates",
"DIRS": [],
"APP_DIRS": True,
"OPTIONS": {
"context_processors": [
"django.template.context_processors.request",
"django.contrib.auth.context_processors.auth",
"django.contrib.messages.context_processors.messages",
],
},
},
]
DATABASES = {
"default": {
"ENGINE": "django.db.backends.sqlite3",
"NAME": BASE_DIR / "db.sqlite3",
}
}
LANGUAGE_CODE = "en-us"
TIME_ZONE = "UTC"
USE_I18N = True
USE_TZ = True
STATIC_URL = "static/"
All lessons in JSON APIs
Practice on your own: Django playground