Python dotenv introduction and tutorial
Last updated on Mar 13, 2023 in Useful Python Modules by Amo Chen ‐ 2 min read
Storing important data in environment variables is a common practice when developing, not only to avoid accidentally committing important data into the codebase, but also to use environment variables to store system or program settings. It is also often used in practice to separate development environment from production environment, for example:
if os. getenv('MODE') == 'development':
# do development-related things
pass
else:
# do production-related things
pass
But as the number of environment variables to be set increases, it may lead to a lot of environment variables to be filled every time you do development. If you have encountered such a situation, why not give python-dotenv a try!
Requirements
- Python 3
- python-dotenv
$ pip install python-dotenv
.env file
The operation of python-dotenv is very simple, by default python-dotenv will load the .env
file, then write the settings into the environment variables, and then you can get the value from the environment variables through os.getenv(key, default=None)
.
Therefore, it is important to prepare the .env
file.
The format of the .env
file is roughly as follows, which is basically the same as setting environment variables in the shell:
export DBHOST=localhost
export DBPORT=5432
Of course, the export
can be omitted in python-dotenv, making the .env
file more concise.
MODE=development
DBHOST=localhost
DBPORT=5432
In addition, python-dotenv also supports the usage of POSIX parameter expansion which allows variables to be embedded in variables, for example:
MODE=development
DBHOST=localhost
DBPORT=5432
DBCONN_STR=${DBHOST}:${DBPORT}
Load .env
file using load_dotenv()
After preparing the .env
, you can easily load the .env
file by calling load_dotenv()
, for example, loading the .env
file in the previous example:
import os
from dotenv import load_dotenv
print('Before load_dotenv()', os.getenv('DBCONN_STR'))
load_dotenv()
print('After load_dotenv()', os.getenv('DBCONN_STR'))
The above program execution result.
$ python dotenv_test.py
Before load_dotenv() None
After load_dotenv() localhost:5432
It can be seen that the environment variable DBCONN_STR
is set after load_dotenv()
.
Above is the usage of python-dotenv, and other more advanced usages such as integration with Django, IPython and even integration with fabric to read remote server configurations. These can be found in the python-dotenv GitHub repo!
Happy Coding!
References
https://github.com/theskumar/python-dotenv