Nitesh Soomani
Nitesh Soomani

Reputation: 652

How to load .env file for different environments in python?

I have three .env files for local, dev and prod environment and I have to load specific environments file while doing deployment for that server i.e If am doing DEV deployment then dev .env file should load all.

Upvotes: 16

Views: 19389

Answers (3)

kta
kta

Reputation: 20130

Initially you have to use an environment variable for that and use it to load correct env file.

import os
from dotenv import load_dotenv
APP_ENV = os.getenv('APP_ENV')
load_dotenv(dotenv_path=f'{BASE_DIR}/.env.{APP_ENV}')

Run your application as below according to whatever app you are using.

export APP_ENV=dev && python3 manage.py runserver 0.0.0.0:8000

Upvotes: 1

akushyn
akushyn

Reputation: 103

Here is my solution how to handle loading different env files for different needs

import os
from pathlib import Path
from dotenv import load_dotenv

APP_ROOT = os.path.join(os.path.dirname(__file__))
PROFILE_DIR = Path(APP_ROOT) / 'profile'
STORAGE_DIR = Path(APP_ROOT) / 'storage'

# add configurations here...

FLASK_ENV = os.getenv('FLASK_ENV') or 'development'

# define here environment config files you want to load
ENVIRONMENTS = {
    'development': '.env',
    'docker': '.env.docker',
}

dotenv_path = os.path.join(APP_ROOT, ENVIRONMENTS.get(FLASK_ENV) or '.env')

# Load Environment variables
load_dotenv(dotenv_path)

Upvotes: 4

Lcj
Lcj

Reputation: 451

You can use the pip module python-dotenv to load .env files.
Here's what you need to do:

from dotenv import load_dotenv

load_dotenv(some_path)

Now the vars in the env file located at some_path can be used with os.getenv

Upvotes: 13

Related Questions