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.
Short Answer
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("VAR") or os.environ["VAR"]
Expanded answer(As proposed by @kevins comment)
You could use an extra environment variable to specify which .env file to use
import os
from dotenv import load_dotenv
env_file = os.environ["DOTENV_FILE"]
load_dotenv(env_file)
Running the script with DOTENV_FILE=local.env will then load local.env
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With