nepalcargoservices.com

Mastering Environment Variable Management with Pydantic

Written on

Chapter 1: Introduction to Pydantic

Pydantic is widely recognized for its data validation capabilities. However, it also simplifies the process of retrieving data from environment variables. Previously, I relied on the python-dotenv library, but I've found Pydantic provides a more efficient and user-friendly approach for accessing environment variables.

Installation of Dependencies

To get started, you'll need to install the necessary libraries. You can do this using the following command:

pip install pydantic-settings

While this library is optional, it enhances the experience by allowing us to load settings or configuration classes directly from environment variables or secret files.

Setting Up Environment Variables

Assuming you already have a .env file in place, here are some sample variables that I will use throughout this article:

DATABASE_URL=http://localhost:8080

SECRET_PASSWORD=123456

Implementing the Logic

Now, let’s implement the logic. You will find it surprisingly straightforward. Using SettingsConfigDict, we can specify the location of our environment file:

from pydantic import Field

from pydantic_settings import BaseSettings, SettingsConfigDict

class Settings(BaseSettings):

model_config = SettingsConfigDict(env_file=".env", env_file_encoding="utf-8") # essential

database_url: str = Field(alias="DATABASE_URL")

secret_password: str = Field(alias="SECRET_PASSWORD")

env_variables = Settings().model_dump()

print(env_variables["database_url"]) # Outputs: http://localhost:8080

print(env_variables["secret_password"]) # Outputs: 123456

If you attempt to omit any variable defined in the settings, an error will occur, enforcing the type checks and eliminating the need for manual validation later on.

pydantic_core._pydantic_core.ValidationError: 1 validation error for Settings

SECRET_PASSWORD

Supporting Multiple .env Files

It's common to manage multiple .env files within a project, such as those for development and production settings. If you have a different file, like .env-prod, you can easily specify it when creating an instance of Settings:

env_variables = Settings(_env_file=".env-prod", _env_file_encoding="utf-8").model_dump()

print(env_variables["database_url"]) # Outputs: prod-url

print(env_variables["secret_password"]) # Outputs: supersecreturl

If you found this article helpful and want to join our expanding community, don’t hesitate to hit the follow button! Your feedback and thoughts are always appreciated.

Join the Stackademic Community

Thank you for reading through! Before you leave, please consider showing your support by clapping and following the author! 👏

Follow us on [X](#) | [LinkedIn](#) | [YouTube](#) | [Discord](#)

Explore more content on: [In Plain English](#) | [CoFeed](#) | [Venture](#) | [Cubed](#)

Discover additional resources at Stackademic.com

Chapter 2: Video Resources

To further enhance your understanding of managing environment variables in Python with Pydantic, check out the following videos:

This video covers various methods for reading environment variables in Python, focusing on Python Dotenv, Python Decouple, and Pydantic.

In this video, learn how to validate environment variables in a Python web application using FastAPI.

Share the page:

Twitter Facebook Reddit LinkIn

-----------------------

Recent Post:

The Amazing Benefits and Historical Significance of Bay Leaves

Explore the history and health benefits of bay leaves, a versatile herb used in cooking and traditional medicine.

How DoorDash Cut Feature Store Expenses by 75% with CockroachDB

DoorDash significantly decreased feature store costs by integrating CockroachDB, achieving a 75% reduction in cloud expenses with improved efficiency.

Ways to Gain Respect and Honor in Today's World

Discover effective methods to earn respect and honor through dedication, risk-taking, and discipline.

# The Wily Fox and the Truthful Chicken: A Lesson on Integrity

A clever fox and an honest chicken teach valuable lessons about honesty and caution.

Understanding the Latest Trends in Phishing Attacks

Explore the top brands targeted by phishing attacks and learn effective prevention strategies.

The Unforeseen Apple Watch Feature That Changed My Perspective

Discover the unexpected feature of the Apple Watch that transformed my daily routine and made it indispensable.

Boosting Your Self-Esteem: Five Effective Strategies

Discover five practical techniques to enhance your self-esteem and overall well-being.

Essential JavaScript Techniques for Beginners

A guide to nine fundamental JavaScript coding techniques for beginners, focusing on simplicity and efficiency.