The best way to handle private keys - a1k89/Blog GitHub Wiki
Prepare
- You have a Django project and ready to deploy it
- You have a many private keys:
- Database username/password
- Twilio username/password
- Django
SECRET_KEY - Another private keys from any services
Solution
Yes, you may to save variable directly in your code. But this is a bad practice. Because Github or another *git solution and transfer private data through it not secure!
- Good choice: 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
But if we restart server we loose Environment variables.
- To resolve it save
Environment variablesto your.bashrcfile (or .zhrc).
I like to use zch. Add to your ~/.zhrc file:
...
export MY_VAR="Private value" # Here!
Reread .zhrc:
source ~/.zhrc
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
.envfile, 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
.envto your.gitignore