PrestonDocks
PrestonDocks

Reputation: 5428

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

Upvotes: 1

Views: 6915

Answers (3)

Benaya Trabelsi
Benaya Trabelsi

Reputation: 361

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.

Upvotes: 1

PrestonDocks
PrestonDocks

Reputation: 5428

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.

Upvotes: 0

GProst
GProst

Reputation: 10237

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)

Upvotes: 3

Related Questions