Andrei Koptev
Posted on April 3, 2021
Prepare
- Django project ready to deploy
- Many private keys:
- Database username/password
- Twilio username/password
- Django
SECRET_KEY
- ... many others
Solution
Yes, you may to save variable directly in your code. But this is a bad practice. Because not secure save keys in Github or another git solution!
1.Use Environment variables
import os
os.environ['MY_VAR'] = 'Private value' # Set key-value
my_var = os.environ.get('MY_VAR') # Read variable value from anywhere
Cons: after restart server we loose Environment variables
2.Save Environment variables
in .bashrc (.zshrc)
Add to your ~/.zshrc
file:
...
export MY_VAR="Private value" # Here!
# source ~/.zshrc
Good. Now we can to read our variable:
import os
my_var = os.environ.get('MY_VAR') # return 'Private value'
Bonus
- For Django use useful
environ-wrapper
: django-environ - Create
.env
file, past private data to it and this is all:
env = environ.Env()
environ.Env.read_env()
SECRET_KEY = env('SECRET_KEY')
# Database
# https://docs.djangoproject.com/en/2.1/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': env('DB_NAME'),
'USER': env('DB_USER'),
'PASSWORD': env('DB_PASSWORD'),
'HOST': 'localhost',
'PORT': '',
}
}
- Don't forget to add
.env
to your.gitignore
💖 💪 🙅 🚩
Andrei Koptev
Posted on April 3, 2021
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.