Keeping Secrets with DECOUPLE

Create a Python virtual environment (folder) and then pip install 'python-decouple'.  

Related Links

Doing much better than your .env file

Using Hydra for configuration files

 

File: 'use_decouple.py':


# use_decouple.py

# pip install python-decouple
#
# Python Decouple is a library that helps you strictly 
# separate the settings parameters from your source code. 
#
# The file '.env' in the root of the project contains the passwords
# and authentication tokens that are private. 
# The file '.env4u.txt' is a template that other users who are
# using your code may use to add their own settings.  It is a
# copy of the '.env' file, but nothing secret to the right of the
# equals sign. 
#
# Must add the settings stored in file '.env' to Git/GitHub 
# .gitignore file so it won't be included in the cloud repository.
#
# “settings.py” is a core file in Django projects.
# See: https://www.pythonpool.com/python-decouple/


#
# Get the secretes in the .env file
from decouple import config

SECRET_KEY = config('SECRET_KEY')
print('SECRET_KEY = "', SECRET_KEY, '"')

# Cast DEBUG text in .env to boolean
DEBUG = config('DEBUG', cast=bool)
print('DEBUG = "', DEBUG, '"  type = ', type(DEBUG))

# Cast EMAIL_PORT text in .env to integer
EMAIL_PORT = config('EMAIL_PORT', cast=int)
print('EMAIL_PORT = "', EMAIL_PORT, '"  type = ', type(EMAIL_PORT))

# Cast LATITUDE text in .env to float
LATITUDE = config('EMAIL_PORT', cast=float)
print('LATITUDE = "', LATITUDE, '"  type = ', type(LATITUDE))

# Get ALLOWED_HOSTS from .env file
ALLOWED_HOSTS = config('ALLOWED_HOSTS', cast=lambda v: [s.strip() for s in v.split(',')])
print('ALLOWED_HOSTS = "', ALLOWED_HOSTS, '"  type = ', type(ALLOWED_HOSTS))
# ALLOWED_HOSTS = " ['.localhost', '.herokuapp.com'] "  type =  <class 'list'>
for host in ALLOWED_HOSTS:
    print('\t"',host,'"')

 

File '.env':


#.env
SECRET_KEY=3izb^ryglj(bvrjb2_y1fZvcnbky#358_l6-nn#i8fkug4mmz!
DEBUG=True
DB_NAME=HELLO_DJANGO
DB_USER=U_HELLO
DB_PASSWORD=hA8(scA@!fg3*sc&xaGh&6%-l<._&xCf
DB_HOST=127.0.0.1
EMAIL_PORT=587
LATITUDE=40.4407
LONGITUDE=-76.1226
ALLOWED_HOSTS=.localhost, .herokuapp.com

 

File '.env4u.txt':


# Rename this file '.env4u.txt' to ".env" and then add it
# to Git/GitHub the .gitignore file so it won't be included 
# your cloud repository.
#
# add your private/secret data to the right of each = sign. 
SECRET_KEY=my_alphanumeric_secret_key
DEBUG=True
DB_NAME=django_db_name
DB_USER=username_db
DB_PASSWORD=password_db
DB_HOST=127.0.0.1
EMAIL_PORT=587
LATITUDE=40.4407
LONGITUDE=-76.1226
ALLOWED_HOSTS=.localhost, .herokuapp.com