So, I had a project recently where I have a bunch of API keys, but I didn’t want to accidentally commit them to a repo (since that would be bad…). But I also wanted the convencience of just in-lining the code, and not have to worry about sourcing environment variables every time I ran the code (since this would inevitably cause annoyances). To solve this, I found a handy tool - python-dotenv, a package which handles all of the complicated bits.
To use python-dotenv you only need to import the library:
from dotenv import load_dotenv
my_api_key = os.getenv('MY_COOL_API_KEY')
The library will automatically load any variables from a
.env file present in the current directory if that file
exits, otherwise it will fall back to real environment variables, meaning that when you put your app into production,
you’ll still be able to configure your code (with 0 code changes).