I am trying to use python-dotenv, but the environment variables I'm trying to pass keep coming up as 'None'. I have two files in the folder: .env & settings.py
I have the following in my .env file:
TEST_VAR=jkh45k3j4h5k34j
And I have the following in the same folder in my settings.py:
import os
from dotenv import load_dotenv
load_dotenv()
test_var = os.getenv("TEST_VAR")
print(test_var)
The output I get when running python3 settings.py
is:
None
Why am I not able to get the variable passed through to settings.py?
By default, it won't overwrite existing environment variables as dotenv assumes the deployment environment has more knowledge about configuration than the application does. To overwrite existing environment variables you can use Dotenv.
You can set default values for environment variables using a .env file, which Compose automatically looks for in project directory (parent folder of your Compose file). Values set in the shell environment override those set in the .env file.
require('dotenv').config() We load the dotenv library and call the config method, which loads the variables into the process.
You have to give the full path to load_dotenv
import os
from dotenv import load_dotenv
# Get the path to the directory this file is in
BASEDIR = os.path.abspath(os.path.dirname(__file__))
# Connect the path with your '.env' file name
load_dotenv(os.path.join(BASEDIR, '.env'))
test_var = os.getenv("TEST_VAR")
print(test_var)
I had the same problem. After quick testing in my code, I noted that
from dotenv import load_dotenv
load_dotenv(".env")
doesn't load .env file properly (that's why it returns None to environment variables). The file is in the same directory.
When used find_dotenv instead of file path/name it works well.
from dotenv import load_dotenv, find_dotenv
load_dotenv(find_dotenv())
For info, find_dotenv is a function that automatically finds .env file.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With