Tutorial: How to Use .env File in FastAPI

9 ott 2023 1 min di lettura
Tutorial: How to Use .env File in FastAPI
Indice dei contenuti

Managing environment variables is crucial in every FastAPI application. The .env file is a useful tool for separating the configuration from the source code. In this guide, we will learn how to use .env file in FastAPI to manage environment variables.

Installation of Dependencies

First of all, you need to install the python-dotenv library to work with .env files in FastAPI:

pip install python-dotenv

Creation of the.env file

Create a file called .env in the root directory of your FastAPI project. In this file, enter the environment variables you want to use:

DB_URL=postgresql://username:password@localhost:5432/mydatabase
 SECRET_KEY=mysecretkey
 DEBUG=True

Reading the.env File in FastAPI

In FastAPI, you can use the BaseSettings class from pydantic to read environment variables from the .env file. Here's how to do it:

from pydantic import BaseSettings

 class Settings(BaseSettings):
 db_url: str
 secret_key: str
 debug: bool

 class Config:
 env_file = ".env"

 settings = Settings()

 # Ora puoi accedere alle variabili d'ambiente come attributi dell'oggetto settings:
 db_url = settings.db_url
 secret_key = settings.secret_key
 debug = settings.debug

Conclusion

In this tutorial, we explored how to manage environment variables in FastAPI using the .env file. By following these steps, you will be able to separate configuration from source code, making your application more secure and easier to manage.

Support us with a

Successivamente, completa il checkout per l'accesso completo a Noviello.it.
Bentornato! Accesso eseguito correttamente.
Ti sei abbonato con successo a Noviello.it.
Successo! Il tuo account è completamente attivato, ora hai accesso a tutti i contenuti.
Operazione riuscita. Le tue informazioni di fatturazione sono state aggiornate.
La tua fatturazione non è stata aggiornata.