DEV Community

Cover image for Python-dotenv (Keep your secrets safe)
Emma Donery
Emma Donery

Posted on • Updated on

Python-dotenv (Keep your secrets safe)

Python-dotenv is a Python module that allows you to specify environment variables in traditional UNIX-like β€œ.env” (dot-env) file within your Python project directory. Read more from their official documentation

Environment variables is the set of key-value pairs for the current user environment. They are generally set by the operating system and the current user-specific configurations.

Python-dotenv helps us work with SECRETS and KEYS without exposing them to the outside world, and keep them safe during development too

ALso, it helps in the development of applications following the 12-factor app principles.


#Create a new virtual environment
python3 -m venv venv
source venv/bin/activate
pip install python-dotenv
Enter fullscreen mode Exit fullscreen mode

Using the python-dotenv module

  1. Create a .env file
    First, you need to create a new .env file, and then load the name and value of the variables as a key-value pairs:

    #.env file
    ID = "12345689"
    SECRET_KEY = "gsabijwjnciiwbjksa"
  2. Create file ,Import and Call python-dotenv

    ## importing the load_dotenv from the python-dotenv module
    from dotenv import load_dotenv
  3. Access the Environment Variables

    from dotenv import load_dotenv
    import os #provides ways to access the Operating System and allows us to read the environment variables
    my_id = os.getenv("ID")
    my_secret_key = os.getenv("SECRET_KEY")
    def myEnvironment():
        print(f'My id is: {my_id}.')
        print(f'My secret key is: {my_secret_key}.')
    if __name__ == "__main__":


ID = "12345689"
SECRET_KEY = "gsabijwjnciiwbjksa"

KEY-NOTE: A large number of security vulnerabilities can be resolved by taking care of leaked credentials, and the python-dotenv helps in developing a safer project environment to work with, both, during and after development as well.

Discussion (0)