3.5. Configuration with Environment Variables#
In the last lab we created a landing page that took values from UNIX environment
variables. In this lab we’ll make some features of Django configurable using
environment variables. You will see in the coming weeks how environment
variables are easy to control in Docker and Kubernetes. All of the changes in
this lab are made in mysite/settings.py. The settings.py file contains
settings that are changed using Python variables. You should be careful when you
edit this file to only change the settings as shown and to not make two copies
of a setting.
Import the os Package#
Add import os near the top of the mystie/settings.py file below the other
imports as shown:
from pathlib import Path
import os # Add me
Imports belong near the top of the file. Their order doesn’t matter.
Find Each Setting#
The settings in this list are already in mysite/settings.py. Find the existing
setting and overwrite it with the ones below:
Make the secret key configurable:
# SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = os.environ.get("SECRET_KEY", "fixme-ansdfnasdfasd8fhu823uirnsdfkn")
Make the
DEBUGmode configurable:# SECURITY WARNING: don't run with debug turned on in production! DEBUG = "DEBUG" in os.environ
Allows requests from anywhere. Possibly too loose for production but needed for GCP health checks:
ALLOWED_HOSTS = [ "*" ]
Make the database location configurable:
DATABASES = { "default": { "ENGINE": "django.db.backends.sqlite3", "NAME": Path(os.environ.get("DATA_DIR", BASE_DIR)) / "db.sqlite3", } }
Configurable Settings#
When you complete this lab the following environment variables control important settings:
Variable |
Purpose |
Note |
|---|---|---|
|
Puts your name on the index page. |
|
|
The URL of your site (e.g. |
|
|
The key used to encrypt session cookies. Must be kept secret or attackers can bypass your login screen. |
|
|
Enables debugging mode, which is less secure but gives application developers important help. (Default off) |
|
|
The place where the |
Remember these variables. You will need them when you build your Dockerfile.