The os.environ.get method is usually what I used to read configuration information in the system environment,
including secrets, in my python scripts. But sometimes (like during testing) it's convenient to use a local file instead.
That's where the python-dotenv library comes in handy.
The library leverages os.environ.get to load variables from a .env file like the system loads them from .profile or .bashrc (in Unix-like systems). By default dotenv looks for the .env file in the same directory as the running program. Note: Always remmember to exclude it from your repo by adding ".env" to your .gitignore. Github's own sample Python.gitignore already does that.
Install:
$ pip install python-dotenv --userImport and use:
import os
from dotenv import load_dotenv
load_dotenv()
client_id = os.getenv('CLIENT_ID')
client_secret = os.getenv('CLIENT_SECRET')Where the .env file looks something like this:
CLIENT_ID="xxxxxxxx"
CLIENT_SECRET="xxxxxxxx"Note that you have to import both os and dotenv.