Python - environment storage
Dotenv storage
Install
- Documentation: python-dotenv · PyPI
- Manual
1
python -m pip install python-dotenv
Setup
- create a
.env
file1
2
3
4
5
6
7
8
9
10# a comment that will be ignored.
REDIS_ADDRESS=localhost:6379
MEANING_OF_LIFE=42
MULTILINE_VAR="hello\nworld"
# you may prefix each line with the word export
# which is totally ignored by this library
CONFIG_PATH=${HOME}/.config/foo
DOMAIN=example.org
EMAIL=admin@${DOMAIN}
DEBUG=${DEBUG:-false} - Load environment variables from a file named
.env
in the current directory or any of its parents or from the path specificied1
2load_dotenv()
# after this any call from os.getenv will get them
Usage example
Add to
settings.py
1
2
3
4
5
6
7
8
9
10
11# settings.py
from dotenv import load_dotenv
load_dotenv()
# OR, the same with increased verbosity
load_dotenv(verbose=True)
# OR, explicitly providing path to '.env'
from pathlib import Path # Python 3.6+ only
env_path = Path('.') / '.env'
load_dotenv(dotenv_path=env_path)After load, you may call the environment variables using
getenv
1
2
3
4# settings.py
import os
SECRET_KEY = os.getenv("EMAIL")
DATABASE_PASSWORD = os.getenv("DATABASE_PASSWORD")