"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > .env file for environment variables in Python

.env file for environment variables in Python

Published on 2024-11-02
Browse:566

Archivo .env para las variables de entorno en Python

In my last personal project I needed to store an API key securely. The most recommended way to do this seems to be to store them as environment variables. Since storing a multitude of environment variables from different projects on my machine is a hassle, I have found a simple alternative with which to handle this situation.

The solution is to use the python-dotenv module, which supports our code to use variables stored in a separate .env file as if they were regular environment variables.

The process is very simple...

1. Create the .env file and give value to the variables.

First of all we create a .env file in which we store the variables:

# Definimos las variables en el archivo .env
VARIABLE1 = "Valor 1"
VARIABLE2 = "Valor 2"

This file can be created either in the root folder or in another location within our project.

2. Import the dotenv module.

We import the dotenv module, and specifically the load_dotenv function into our project. We will also have to import the os module to import the environment variables once the content of the .env:
is loaded.

from dotenv import load_dotenv
import os

Since it is not a native Python module, it requires being installed through Pip, with the command pip install python-dotenv.

3. Recover the variables.

The load_dotenv() function loads the variables into the program as environment variables. Using the module we can recover their values ​​and assign them to variables within the project:

# Cargamos las variables del archivo como variables de entorno.
load_dotenv() 

# Se almacena el valor "Valor 1" de la primera variable.
VARIABLE1 = os.getenv("VARIABLE1")  

# Otra forma de recuperar el valor de la variable.
VARIABLE2 = os.environ.get("VARIABLE2")  

If the .env file is not located in the same path where the code is executed, we must define the location of the file:

load_dontenv(path="ruta/.env")
Release Statement This article is reproduced at: https://dev.to/itcrow/archivo-env-para-las-variables-de-entorno-en-python-502g?1 If there is any infringement, please contact [email protected] to delete it
Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3