The Scenario
I am currently doing the 100 Days of Code challenge using Angela Yu’s Udemy course. In the morning before work starts I do a little bit of it on my MS Windows desktop:
In the evening I’ll commit my changes to my GitHub repository & step away from the desk. After dinner and shenanigans I’ll continue to do the project using my MacBook. I pull for the days changes (on the windows box) and pick up where I left off.
The Problem
Because I’m committing to a public repository:
- I don’t want to embed any usernames, passwords, API keys, or other types of user IDs into the code I’m committing. There are bots constantly crawling public repos looking for this kind of info to exploit.
- I also don’t want to use local OS specific environment variables because I’m switching operating systems at least once a day.
The Solution: .env files!
A .env file is a text file in which the variables are defined, one per line. The format the file is exactly the same under both OSes so my workflow is the same.
The process is as follows:
Make sure you have .env in your .gitignore – if you don’t do this your .env file will get committed along with the rest of your files:
Install the python-dotenv package into your project:
pip install python-dotenv
Now you can (1) import dotenv (2) use load_dotenv on your target file (3) grab variables from the file when you need them!