One common issue with python programming is the need to use passwords, API keys, or other credentials in python code. However, you do not want to make these passwords, keys, and credentials public. So, using environment variables is the best practice. Then, the code can get the environmental variables from the operating system environment. The python-dotenv module reads in environment variables from a .env file.
Never put .env files on the GitHub repository. For this reason, you must include .env in the .gitignore file.
So in the .gitignore file,
You may also want to exclude everything in the env_var_folder.
Another common practice is to create an ENV folder that GitHub ignores.
Format of .env File
The format of an .env file is simple. In each line, you set a variable equal to a value. The value is in parenthesis if it is a string and outside parenthesis if it is numeric. Put environment variables in all caps to set them apart from more common python variables.
SECRET_PHRASE=”Remember the Titans”
First, import python-dotenv. Notably, importing requires a different name (dotenv) than used when installing with pip
The easiest way to access the environment variables in the .env file is to call load_dotenv when the application starts. So you will need to use the command,
from dotenv import load_dotenv
You will also need the os module to make a relative path to the .env file. So,
Next, use os.path.join to make the relative path to the file.
Then, call the load_dotenv function.
Keep the same variable name inside your python code for simplicity.
So, throughout the rest of the application, you will know that SECRET_PHRASE is an environment variable.
While this works when running on your system, a remote server will need to use other methods to get environment variables when running your application. Running the command load_dotenv will give you an error if the file doesn’t exist on the server.
So, you will need to ensure that the file exists before you run the command.
This way, you will not get an error when you deploy and run on a remote server without the .env file.
Google Cloud and Heroku have their own ways of dealing with confidential information and environment variables. I will not cover environmental variables and secrets in Heroku and Google Cloud in future posts.
python-dotenv 0.15.0. (2020, October 28). Featured on PyPi. Retrieved from https://pypi.org/project/python-dotenv/
Robinson, S. Git: Ignore Files with .gitignore. Featured on StackAbuse. Retrieved from https://stackabuse.com/git-ignore-files-with-gitignore/