3

I'm using python-dotenv to set up environment variables and I got everything to work. I can now call my environment variables from settings.py that I defined in .env. That's cool and all but is there a way to call the environment variables from other files in subdirectories? Note that I'm not using django or any framework.

# settings.py

import os
from dotenv import load_dotenv
BASEDIR = os.path.abspath(os.path.dirname(__file__))
load_dotenv(os.path.join(BASEDIR, '.env'))

CLIENT_ID = os.getenv("CLIENT_ID")

# This works!
print(CLIENT_ID)
# other_file.py

import os

CLIENT_ID = os.getenv("CLIENT_ID")

# This does not :(, prints None
print(CLIENT_ID)

I'm sure I can load .env in every file where env variables are needed, but is there a more efficient way?

dc115
  • 127
  • 1
  • 9
  • https://stackoverflow.com/questions/4906977/how-to-access-environment-variable-values?rq=1 – OneCricketeer Dec 25 '19 at 05:59
  • @cricket_007 `os.getenv` only works in `settings.py`. I'm assuming it's because I loaded the `.env` file there. Is it best practice to load `.env` every time I need to call an environment variable or is there a better way? – dc115 Dec 25 '19 at 06:08
  • It should work in your entire program after the settings file is loaded... Why can't you import settings from other scripts? – OneCricketeer Dec 25 '19 at 13:21

1 Answers1

0

You would have to know the path of the .env file relative to the subdirectory, import dotenv and load_dotenv({path}). For example, if your .env is in /, and other_file.py is in /subdir1/subdir2/ (/subdir1/subdir2/other_file.py), then you would have to

from dotenv import load_dotenv
load_dotenv('../../.env')