4.3. 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:

  1. Make the secret key configurable:

    # SECURITY WARNING: keep the secret key used in production secret!
    SECRET_KEY = os.environ.get('SECRET_KEY', 'fixme-ansdfnasdfasd8fhu823uirnsdfkn')
    
  2. Make the DEBUG mode configurable:

    # SECURITY WARNING: don't run with debug turned on in production!
    DEBUG = bool(os.environ.get('DEBUG', True))
    
  3. Allows requests from anywhere. Possibly too loose for production but needed for GCP health checks:

    ALLOWED_HOSTS = [ "*" ]
    
  4. 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

STUDENT_NAME

Puts your name on the index page.

SITE_NAME

The URL of your site (e.g. www.mysite.com).

SECRET_KEY

The key used to encrypt session cookies. Must be kept secret or attackers can bypass your login screen.

SECRET_KEY

DEBUG

Enables debugging mode, which is less secure but gives application developers important help. (Default on)

DEBUG

DATA_DIR

The place where the db.sqlite3 data is located. A new one will be created if it doesn’t exist.

Remember these variables. You will need them when you build your Dockerfile.