Using .env files within Python
I have been trying a lot of Node.js tutorials, putting my hands to learning a new skill and all that, especially during COVID-19. Using enviroment variables has always been easy in node especially with packages such as dotenv which allows getting your variables from your .env
file with ease.
// .env
DB_HOST=localhost
// nodeFile.js
require('dotenv').config()
const db = host: process.env.DB_HOST,
But when using enviroment variables within Python, I have always found that a little tricky, mainly because if you're in an virtual enviroment and you set variables in that enviroment. Once you stop it, they're forgotten.
This is of course unless you keep them in your .zsh
file. But then if you upload your dotfiles to Github they're stored in the repo.
Enter python-dotenv
a sweet package from Saurabh Kumar that allows you to use .env
within your Python projects. Whilst I am working through node tutorials, I still like to brush up on my Python. Having a package like this has made my life a tone easier when it comes to managing keys.
Let me walk you through how to get set up
Install the latest version
pip install -U python-dotenv
Assuming you have created the .env
file along-side your settings module.
.
├── .env
└── settings.py
Add the following code to your settings.py
# 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 # python3 only
env_path = Path('.') / '.env'
load_dotenv(dotenv_path=env_path)
At this point, parsed key/value from the .env
file is now present as system environment variable and they can be conveniently accessed via
os.getenv()
:
# app.py
import os
SECRET_KEY = os.getenv("EMAIL")
DATABASE_PASSWORD = os.getenv("DATABASE_PASSWORD")
You can find more information about python-dotenv
via the repo. I think this is a great package, and i'll be using it in all my Python development.