Secure Django with Environment Variables
2 min read
python
django
When pushing your web application to production or even GitHub, it is a good idea to keep your API keys or other sensitive information away from prying eyes. Creating environment variables is a great way to do this and the python-decouple package makes it easy for us. To install, cd into your project and activate your virtual environment if you have one.
pip install python-decouple
Next, create a .env file at the root of your project and add any environment variables you wish. Here is an example .env file:
SECRET_KEY=secretkeyvalue
DEBUG=True
EMAIL_BACKEND=django.core.mail.backends.smtp.EmailBackend
DEBUG=True
EMAIL_BACKEND=django.core.mail.backends.smtp.EmailBackend
EMAIL_HOST=smtp.gmail.com
EMAIL_PORT=587
EMAIL_USE_TLS=True
EMAIL_HOST_USER=user@gmail.com
EMAIL_HOST_PASSWORD=password
DBNAME=testdb
DBUSER=testuser
DBPASSWORD=password
DBHOST=localhost
In your settings.py file, import python-decouple like so.
from decouple import config
Still in your settings.py file, here is an example of how to access the values in your .env file.
SECRET_KEY = config('SECRET_KEY')
With python-decouple you can cast values with the cast argument as well as set default values in case the .env can't find the value or it is missing entirely.
DEBUG = config('DEBUG', default=False, cast=bool)
An extended example would be if you were to set up a database with Postgres, you would access your .env values like this.
DATABASES = {
'default': {`
'ENGINE': 'django.db.backends.postgresql',
'NAME': config('DBNAME'),
'USER': config('DBUSER'),
'PASSWORD': config('DBPASSWORD'),
'HOST': config('DBHOST') }
}
With this set up you can easily post the source code to GitHub without worrying about exposing your application's secret key or any other sensitive information. Just make sure you have a .gitignore file that doesn't upload the .env file! Hopefully, this helps and makes your Django application that much more secure.