DEV Community

loading...

How to store passwords and keys in your project

a1k89 profile image Andrei Koptev Updated on ・1 min read

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
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

Good. Now we can to read our variable:

import os

my_var = os.environ.get('MY_VAR') # return 'Private value'
Enter fullscreen mode Exit fullscreen mode

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': '',
    }
}
Enter fullscreen mode Exit fullscreen mode
  • Don't forget to add .env to your .gitignore

Discussion (0)

Forem Open with the Forem app