Table of Contents
Motivation
Whether you need credentials to log into a system or some configuration parameters for your application, the .env concept might help you.
Installation
pip install python-dotenv
Usage
.env file
Create an .env file in your project root folder
You should not share this file or commit/push it to your version control. You should add it to the .gitignore file to avoid adding it to version control or public repository accidentally.
The content of the file contains key-value pairs like the following
FOO="BAR" DB_USERNAME="JOBO" SECRET_KEY="adf6g96dfg6a6df8g0"
Implementation
from dotenv import load_dotenv import os def test_read_credentials(): load_dotenv() assert os.environ.get("FOO") == "BAR" assert os.environ.get("DB_USERNAME") == "JOBO" assert os.getenv("DB_USERNAME") == "JOBO" assert os.environ.get("SECRET_KEY") == "adf6g96dfg6a6df8g0"
Caveats
The OS/system’s environment variables always override .env configurations by default as the following example.
os.getenv("USERNAME")
will always return your system user