Home >Backend Development >Python Tutorial >.env file for environment variables in 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...
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.
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.
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")
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!