Home > Backend Development > Python Tutorial > .env file for environment variables in Python

.env file for environment variables in Python

PHPz
Release: 2024-09-10 22:35:02
Original
333 people have browsed it

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"
Copy after login

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
Copy after login

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")  
Copy after login

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")
Copy after login

The above is the detailed content of .env file for environment variables in Python. For more information, please follow other related articles on the PHP Chinese website!

source:dev.to
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template