Read Variables from .env File using Pydantic
In this article, we will learn how to read variables from an .env file, leveraging Pydantic. Pydantic is a data validation library that is perfect for working with configuration files, such as the .env file, which typically stores sensitive information like API keys, database credentials, and other application settings.
What is a .env File?
A .env file is a simple text file with key-value pairs of environment variables. It allows developers to store important configuration data outside of the codebase, ensuring proper separation of concerns.
Why Use Pydantic?
Pydantic makes it easy to handle configuration files by providing a convenient way to define models, which can be used to validate and parse the variables from the .env file. Furthermore, Pydantic eases the type checking and data validation of inputs and settings.
Getting Started with Pydantic
To utilize Pydantic effectively, you'll first need to install the package. To do this, you can use the following pip command:
pip install pydantic
Creating a Settings Class using BaseSettings
After installing Pydantic, you can start by creating a Settings class with BaseSettings as the base class. For example, let's assume you have the following .env file:
aaa=value1
bbb=value2
You can define a Settings class using the following code:
from pydantic import BaseSettings
class Settings(BaseSettings):
aaa: str = "default_value1"
bbb: str = "default_value2"
Reading Variables from the .env File
After defining the settings class, you can now read the variables from the .env file by using the .from_env() method:
import os
from pydantic_settings import Settings
if os.path.exists(".env"):
os.environ["env_file"] = ".env"
test_vars = Settings()
Using the Variables in your Code
Now, you can use the variables directly in your code:
from pydantic_settings import Settings
def my_function():
my_aaa_value = Settings().aaa
my_bbb_value = Settings().bbb
# do something with the values
Key Concepts
- BaseSettings: The base class for creating Pydantic settings models.
- Settings class: A custom class derived from
BaseSettingsto define the environment variables for your project. -
.from_env(): The method that Pydantic provides to initialize a settings class instance based on the .env file variables.