Reading environment variables from more than one ".env" file in Python

Question:

I have environment variables that I need to get from two different files in order to keep user+pw outside of the git repo. I download the sensitive user+pass from another location and add it to .gitignore.

I am using

from os import getenv
from dotenv import load_dotenv
    
    ...
    load_dotenv()
    DB_HOST=getenv('DB_HOST') # from env file 1
    DB_NAME=getenv('DB_NAME') # from env file 1
    DB_USER=getenv('DB_USER') # from env file 2
    DB_PASS=getenv('DB_PASS') # from env file 2

and I have the two ".env" files in the folder of the python script.

env_file.env contains:

DB_HOST=xyz
DB_NAME=abc

env_file_in_gitignore.env which needs to stay out of the git repo but is available by download using an sh script:

DB_USER=me
DB_PASS=eao

How to avoid the error:

TypeError: connect() argument 2 must be str, not None
connect() argument 2 must be str, not None

which is thrown since one of the two files are not used for the .env import?

How can I get environment variables from two different ".env" files, both stored in the working directory?

Asked By: questionto42

||

Answers:

You can add file path as an argument in load_dotenv function

from dotenv import load_dotenv
import os

load_dotenv(<file 1 path>)
load_dotenv(<file 2 path>)
Answered By: tax evader

there is a method load env file is load_dotenv you can use as many env file you want using

from dotenv import load_dotenv

load_dotenv('path1')
load_dotenv('path2)
...

for more information read this

Answered By: Jay Patel

I implemented reading env values from multiple env files by using if statements as below.

I put basic stuffs in .env file and local and prod settings in respective .env.local or .env.prod file

# Import and load environment variables
from dotenv import load_dotenv
load_dotenv() # Load .env file

# Need to check and return boolean, so check for String "True"
APP_ENVIRONMENT = os.getenv("DEBUG") == "True"

if APP_ENVIRONMENT:
    load_dotenv(".env.local")
else:
    load_dotenv(".env.prod")
Answered By: Neeraj
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.