Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 876
questionto42standswithUkraine Avatar asked May 09 '26 00:05

questionto42standswithUkraine


2 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>)
like image 88
vht981230 Avatar answered May 10 '26 14:05

vht981230


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")
like image 43
Neeraj Avatar answered May 10 '26 15:05

Neeraj



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!