简体   繁体   中英

python-dotenv not working in custom package

I have been using python-dotenv successfully in my python app. I am now starting to refactor and creating packages to hold some of my support files. When i move the .env file into the package folder my env variables are not set.

As an example

The following structure works.

/
- app.py
- .env
#app.py
import os
from dotenv import load_dotenv
load_dotenv()
print(os.getenv("DB_PASSWORD"))

Result: kdfhsffdfjd

The following structure does not work

/
- database
  - __init__.py
  - connection.py
  - .env
- app.py
#connection.py
import os
from dotenv import load_dotenv
load_dotenv()
print(os.getenv("DB_PASSWORD"))

Result: None

# app.py
from database import connection

You need to actually call load_dotenv function. You can pass the .env file path as an argument or you could try to use find_dotenv method:

from dotenv import load_dotenv, find_dotenv
load_dotenv(find_dotenv())

# or
load_dotenv(path_to_dotenv_file)

The solution was to keep the .env file in the root of my project. This makes sense on a number of levels.

  1. It ensures that only one .env file exists.
  2. The whole point of the .env file is that I don't want to publish my secrets in the Git repo. If the .env file was located in the package, users would have to edit the package by adding a .env file, potentially in multiple places.

Anyway, in summary, I can still use load_dotenv() in the package, but the .env file had to be in the root of the project. @GProst has suggested that I should be able to access it in the package, but I was not able to get that to work.

for future reference, I had the same problem, but none of the above helped - I was using pipenv, and it turns out I that when I was running the pipenv shell from another location, which isn't the project root folder, it wouldn't load antything from the .env file. after deactivating the shell, and running it again from the root folder, it worked fine.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM