SoFunction
Updated on 2025-04-14

Pydantic and .env file management environment configuration

Pydantic is a Python third-party package for data verification and setup management. It automatically verifies and parses data through type annotations, ensuring that the data meets the expected format and can generate clear error messages.

Here we mainly introduce the use of Pydantic and .env files to manage environment configuration.

1. Install the dependency library

When Pydantic is in the first version, you can install the Pydantic library, and after the second version, the settings-related functions are split into independent packages. The independent bag is calledpydantic-settings, the latest version is 2.8.1.

Now you only need to install the pydantic-settings package, and the installation command is as follows:

pip install pydantic-settings==2.8.1

When installing the pydantic-settings package, other pydantic, python-dotenv and other dependency packages will be automatically installed.

2. Create .env file

Create a .env file and fill in the corresponding content according to the specific project needs. For example:

DATABASE_URL=your_database_url
DATABASE_USERNAME=your_username
DATABASE_PASSWORD=your_password

3. Create a file

Create a file, and create a Settings class in it, which inherits from the BaseSettings class of pydantic_settings. The Settings class adds the same class attribute as the environment variable in the .env file, and creates a model_config class attribute, and initializes the class attribute with SettingsConfigDict.

The code is as follows:

from pydantic_settings import BaseSettings, SettingsConfigDict  
  
  
class Settings(BaseSettings):  
    DATABASE_URL: str  
    DATABASE_USERNAME: str  
    DATABASE_PASSWORD: str  
  
    model_config = SettingsConfigDict(  
        env_file=".env"  
    )

To facilitate the configuration, you can also add aget_settings()The function, as shown below:

def get_settings():  
    return Settings()

The test code is as follows:

if __name__ == '__main__':  
    settings = get_settings()  
    assert settings.DATABASE_URL == "your_database_url"  
    assert settings.DATABASE_USERNAME == "your_username"  
    assert settings.DATABASE_PASSWORD == "your_password"

4. Add prefix to environment variables to distinguish different environments

One reason to use .env files to configure environment variables is to avoid sensitive data being written directly into the code (safety); one reason is to avoid hard-code variables directly into the code, so that they can be modified when needed; another reason is to obtain different environment variables under different execution environments.

In the above code, only one value is set for each environment variable. So how do you set a different value for each variable?

You can prefix environment variables to distinguish different execution environments. For example, use in production environmentPROD_Prefix, use in the development environmentDEV_Prefix.

When initializing the model_config class attribute, the SettingsConfigDict class is addedenv_prefixParameter, value is("ENVIRONMENT_PREFIX", "DEV_"). It means that the environment variable will be firstENVIRONMENT_PREFIXRead the prefix. If it cannot be read, it is used by default.DEV_Prefix.

At the same time, the SettingsConfigDict class adds an extra parameter, and its value is "allow". Because Pydantic will ignore fields that are not defined in the model by default (i.e.extra="ignore"), these fields will not be checked or stored. When set toextra="ignore"After that, the model will accept and retain undefined fields, store them as dynamic attributes, but will not perform type verification.

Note: Addedenv_prefixAfter the attributes, remember to set them as neededENVIRONMENT_PREFIXThis environment variable.

The code is as follows:

	#Other code...	model_config = SettingsConfigDict(  
	    env_prefix=("ENVIRONMENT_PREFIX", "DEV_"),  
	    env_file=".env",  
	    extra="allow"  
	)

5. The final complete code

A complete code example for .env files:

DEV_DATABASE_URL=your_database_url  
DEV_DATABASE_USERNAME=your_username  
DEV_DATABASE_PASSWORD=your_password  
  
PROD_DATABASE_URL=prod_your_database_url  
PROD_DATABASE_USERNAME=prod_your_username  
PROD_DATABASE_PASSWORD=prod_your_password

Complete code example:

import os  
  
from pydantic_settings import BaseSettings, SettingsConfigDict  
  
  
class Settings(BaseSettings):  
    DATABASE_URL: str  
    DATABASE_USERNAME: str  
    DATABASE_PASSWORD: str  
  
    model_config = SettingsConfigDict(  
        env_prefix=("ENVIRONMENT_PREFIX", "DEV_"),  
        env_file=".env",  
        extra="allow"  
    )  
  
  
def get_settings():  
    return Settings()  
  
  
if __name__ == '__main__':  
    settings = get_settings()  
    prefix = ("ENVIRONMENT_PREFIX", "DEV_")  
    if prefix == "DEV_":  
        assert settings.DATABASE_URL == "your_database_url"  
        assert settings.DATABASE_USERNAME == "your_username"  
        assert settings.DATABASE_PASSWORD == "your_password"  
    elif prefix == "PROD_":  
        assert settings.DATABASE_URL == "prod_your_database_url"  
        assert settings.DATABASE_USERNAME == "prod_your_username"  
        assert settings.DATABASE_PASSWORD == "prod_your_password"

This is the article about Pydantic and .env file management environment configuration. For more related Pydantic .env environment configuration content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!