
上QQ阅读APP看书,第一时间看更新
How to do it...
To read sensitive settings from the environment variables, perform these steps:
- At the beginning of settings/_base.py, define the get_secret() function as follows:
# settings/_base.py
import os
from django.core.exceptions import ImproperlyConfigured
def get_secret(setting):
"""Get the secret variable or return explicit exception."""
try:
return os.environ[setting]
except KeyError:
error_msg = f'Set the {setting} environment variable'
raise ImproperlyConfigured(error_msg)
- Then, whenever you need to define a sensitive value, use the get_secret() function, as shown in the following example:
SECRET_KEY = get_secret('DJANGO_SECRET_KEY')
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': get_secret('DATABASE_NAME'),
'USER': get_secret('DATABASE_USER'),
'PASSWORD': get_secret('DATABASE_PASSWORD'),
'HOST': 'db',
'PORT': '5432',
}
}