Reputation: 548
I tried to load environment variables from a file named .env to settings.py file here i created the .env file and settings file same folder.
this is my .env file
DEBUG=on
SECRET_KEY=ksmdfw3324@#jefm
DATABASE_URL=psql://urser:[email protected]:8458/database
SQLITE_URL=sqlite:///my-local-sqlite.db
CACHE_URL=memcache://127.0.0.1:11211,127.0.0.1:11212,127.0.0.1:11213
REDIS_URL=rediscache://127.0.0.1:6379/1?
client_class=django_redis.client.DefaultClient&password=ungithubbed-secret
MYSQL_DATABASE = student
MYSQL_USERNAME = root
SECRET_KEY=secret-key
this is my setting.py file
import os
from os.path import join, dirname
from dotenv import load_dotenv
dotenv_path = join(dirname(__file__), '.env')
load_dotenv(dotenv_path)
# Accessing variables.
dbname = os.getenv('MYSQL_DATABASE')
secret_key = os.getenv('SECRET_KEY')
# Using variables.
print(dabname)
print(secret_key)
i installed pip install -U python-dotenv
Issue is i am not able to get environment variable inside settings file
while trying python manage.py runserver
i am getting this error
C:\Users\mehul\AppData\Local\Programs\Python\Python36-32\lib\site-
packages\dotenv\main.py:65: UserWarning: File doesn't exist
warnings.warn("File doesn't exist {}".format(self.dotenv_path))
Traceback (most recent call last):
File "manage.py", line 28, in <module>
execute_from_command_line(sys.argv)
File "C:\Users\mehul\AppData\Local\Programs\Python\Python36-32\lib\site-
packages\django\core\management\__init__.py", line 371, in
execute_from_command_line
utility.execute()
File "C:\Users\mehul\AppData\Local\Programs\Python\Python36-32\lib\site-
packages\django\core\management\__init__.py", line 317, in execute
settings.INSTALLED_APPS
File "C:\Users\mehul\AppData\Local\Programs\Python\Python36-32\lib\site-
packages\django\conf\__init__.py", line 56, in __getattr__
self._setup(name)
File "C:\Users\mehul\AppData\Local\Programs\Python\Python36-32\lib\site-
packages\django\conf\__init__.py", line 43, in _setup
self._wrapped = Settings(settings_module)
File "C:\Users\mehul\AppData\Local\Programs\Python\Python36-32\lib\site-
packages\django\conf\__init__.py", line 106, in __init__
mod = importlib.import_module(self.SETTINGS_MODULE)
File "C:\Users\mehul\AppData\Local\Programs\Python\Python36-
32\lib\importlib\__init__.py", line 126, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
File "<frozen importlib._bootstrap>", line 994, in _gcd_import
File "<frozen importlib._bootstrap>", line 971, in _find_and_load
File "<frozen importlib._bootstrap>", line 955, in _find_and_load_unlocked
File "<frozen importlib._bootstrap>", line 665, in _load_unlocked
File "<frozen importlib._bootstrap_external>", line 678, in exec_module
File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
File "C:\xampp\htdocs\epitastudent\epitastudent\settings.py", line 25, in
<module>
load_dotenv()
File "C:\Users\mehul\AppData\Local\Programs\Python\Python36-32\lib\site-
packages\dotenv\main.py", line 255, in load_dotenv
return DotEnv(f,
verbose=verbose).set_as_environment_variables(override=override)
File "C:\Users\mehul\AppData\Local\Programs\Python\Python36-32\lib\site-
packages\dotenv\main.py", line 98, in set_as_environment_variables
os.environ[k] = v
File "C:\Users\mehul\AppData\Local\Programs\Python\Python36-32\lib\os.py",
line 675, in __setitem__
self.putenv(key, value)
ValueError: embedded null character
I am not sure how to create development and production environment variable and about this embedded null character. pls help me any one Thanks in advance
Edit: I got now .env file to inside settings
import os
import environ
root = environ.Path(__file__) - 3 # three folder back (/a/b/c/ - 3 = /)
env = environ.Env(DEBUG=(bool, False),) # set default values and casting
environ.Env.read_env() # reading .env file
print(os.getenv('DATABASE_NAME'))
How can i differentiate development env credentials and production credentials
Upvotes: 9
Views: 20614
Reputation: 531
First ensure that .env
file in the base directory of your project, which is the same directory as manage.py
.
To load the .env
file in your settings.py
, use the following code:
from pathlib import Path
import dotenv
# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent
# Load .env file
ENV_FILE_PATH = BASE_DIR / ".env"
dotenv.read_dotenv(str(ENV_FILE_PATH))
# load value from .env file
SECRET_KEY = os.environ.get("PRODUCTION_SECRET_KEY")
Note: In the .env
file, if a value contains #
, it will only read the string up to the #
.
For example, in the .env
file:
SECRET_KEY=12sad&6#dsds
It will only read 12sad
and not the full string. To include the full string, enclose it in double quotes(""
) or single quotes (''
):
SECRET_KEY='12sad&6#dsds'
You can test if it's working after setting up in settings.py
using the Django shell command python manage.py shell
:
>>> import os
>>> os.environ.get("SECRET_KEY")
'12sad&6#dsds'
Upvotes: 2
Reputation: 1131
For future Googlers here's another approach. Inside manage.py
add:
from dotenv import load_dotenv
load_dotenv()
Now you can do the following anywhere else in your project (including settings.py
) to get access to environment variables:
import os
os.environ.get("NAME")
Upvotes: 13
Reputation: 491
I was unable to load environment variables using load_dotenv() in Python version 3.5 - later versions were working fine.
The workaround is explicitly include the folder containing .env in the path. So, assuming folder project contains .env, settings.py will have following lines:
import os
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
from dotenv import load_dotenv
load_dotenv(os.path.join(BASE_DIR, "project", ".env"))
Upvotes: 3
Reputation: 851
I think there are mainly two packages to use
pip install django-environ
and
pip install python-dotenv
I choose to use dotenv, as django-environ give me some error.
Error: The SECRET_KEY setting must not be empty
Below is my working solution, notice that it is square bracket []
when calling os.environ.
My version is Django==2.2.6, python==3.7.5
settings.py
import os
from dotenv import load_dotenv
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
load_dotenv(os.path.join(BASE_DIR, '.env'))
SECRET_KEY = os.environ['SECRET_KEY']
and the .env file is storing in the current directory with
.env
export SECRET_KEY="xxxxxx"
export DB_NAME = "xxx"
Upvotes: 5
Reputation: 161
Try this instead:
import os
import environ
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
environ.Env.read_env(env_file=os.path.join(BASE_DIR, '.env'))
Upvotes: 11
Reputation: 51
I'm not quite sure, but maybe it has to do with the path to the .env file. Maybe you should try in settings.py:
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(file)))
dotenv_path = os.path.join(BASE_DIR, file.env)
Upvotes: 0