If you look at modern code deployment practices, like in the 12 factor
app, environment variables are very important for keeping secret information, or specific information set for a server. All while not having long settings in a settings file —files, or every single server and host. It helps keep things simple and clean in your code along with the following quoted from the 12factorapp site:
- Resource handles to the database, Memcached, and other backing services
- Credentials to external services such as Amazon S3 or Twitter
- Per-deploy values such as the canonical hostname for the deploy
What Are Environment Variables?
Environment variables are a key:value pairs that can affect how a program runs.
They need to be set at some point before a process is run so the process can read them in and act accordingly. A lot of times in production environments your database name and passwords are set as environment variables so that information does not end up in a code repository somewhere. Unfortunately it do es even publicly sometimes.
By relying on an environment variable your code doesn't care what your settings are because you can set them some other point. Actually working with environment variables is really simple. All you need to start is importing native os module:
import os
.
import os
name = os.environ.get('USER')
OK but where to put and find these variables in your os? There are a
lot of ways but below 2 I think have best implementations:
1 - Virtual Environment
One of the best ways is to get them from virtual environment. When you activate your virtual env source .venv/bin/activate
, "activate" script runs. You can add below script to the end of this activate file:
export $(grep -v '^#' ./.env | xargs)
Where ./
is your project "root directory". So if you have more than one env
files you can add them too as below:
export $(grep -v '^#' ./.env | xargs)
export $(grep -v '^#' ./.envs/.env.dev | xargs)
I usually use this method but this requires an Unix-like OS
(MacOS & Linux etc).
2 - Django-Environ Module Library
django-environ module allows you to use Twelve-factor
methodology to configure your Django application with
environment variables.
In your project settings.py
import environ
env = environ.Env()
# reading .env file
env.read_env(env.str('./', '.env'))
# https://docs.djangoproject.com/en/dev/ref/settings/#secret-key
SECRET_KEY = env('DJANGO_SECRET_KEY')
In addtion to all of these above you can export your env vars
via .bashrc
or .bash_profile
or even .profile
but this would be a bad practice: using project wide restrictions over system wide.
Top comments (0)