Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Environment variable coming up as 'None" using dotenv python

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?

like image 479
user196286 Avatar asked May 15 '18 16:05

user196286


People also ask

Does dotenv override environment variables?

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.

Can I use variables in .env file?

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.

What does dotenv config () do?

require('dotenv').config() We load the dotenv library and call the config method, which loads the variables into the process.


2 Answers

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)
like image 92
KevinS Avatar answered Oct 15 '22 22:10

KevinS


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.

like image 42
industArk Avatar answered Oct 16 '22 00:10

industArk