Dec. 21, 2022

How to automatically change environment variables for dev and production


More on:   
Go back

Post Image
When running a Django website in production, some environment variables need to stay private. For example the SECRET_KEY and the password of the database (if using a different database than sqlite). These variables are set in the settings.py file of the project.

In addition, the database can be sqlite when running locally, and mySQL or PostgreSQL when in production. The variable DEBUG has to be set to False in production, and so on.

I keep the environment variables in two separate files. In the example bellow, the names of the files are .my_localenv and .my_liveenvironment.

I use socket to find out if the environment that is running is local or production.
My local environment’s name starts with “Deas”.
To find out the name of the local environment, run python in the terminal and import socket. Then print socket.gethostname().

Finally, I use the library python-dotenv to load the environment variables to my virtual environment.

A partial example of the local environment file, would look something like this:
DEBUG=True
SECRET_KEY=xyz
NAME=db.sqlite3

The settings.py file starts like the following:

import os
from dotenv import load_dotenv
import socket

#Select local or live environment to get variables
if socket.gethostname().startswith('Deas'):

    load_dotenv(dotenv_path=BASE_DIR/".my_localenv")
    DATABASES = {
        "default": {
            "ENGINE": os.getenv("ENGINE"),
            "NAME": BASE_DIR / str(os.getenv("NAME")),
        }
    }
else:

    load_dotenv(dotenv_path=BASE_DIR/".my_liveenvironment")

    DATABASES = {
        'default': {
            "ENGINE": os.getenv("ENGINE"),
            "NAME": str(os.getenv("NAME")),
            'USER': os.getenv("USER"),
            'PASSWORD': os.getenv("PASSWORD"),
            'HOST': os.getenv("HOST"),
        }
    }

SECRET_KEY = os.getenv("SECRET_KEY")

DEBUG = os.getenv("DEBUG")