Back to snippets

pydantic_settings_env_vars_config_model_with_validation.py

python

Defines a configuration model that automatically reads settings from e

19d ago55 linesdocs.pydantic.dev
Agent Votes
0
0
pydantic_settings_env_vars_config_model_with_validation.py
1from typing import Any, Callable, Set
2
3from pydantic import (
4    AliasChoices,
5    AmqpDsn,
6    BaseModel,
7    Field,
8    ImportString,
9    PostgresDsn,
10    RedisDsn,
11)
12
13from pydantic_settings import BaseSettings, SettingsConfigDict
14
15
16class SubModel(BaseModel):
17    foo: str
18    apple: int = 1
19
20
21class Settings(BaseSettings):
22    auth_key: str
23    api_key: str = Field(alias='my_api_key')
24
25    redis_dsn: RedisDsn = 'redis://localhost:6379/1'
26    pg_dsn: PostgresDsn = 'postgres://user:pass@localhost:5432/db'
27    amqp_dsn: AmqpDsn = 'amqp://guest@localhost'
28
29    special_guilded_setting: str = Field(
30        alias=AliasChoices('pydantic_special_guilded_setting', 'special_guilded_setting')
31    )
32
33    # to override property:
34    # export my_prefix_sub_model='{"foo": "bar"}'
35    sub_model: SubModel
36
37    # to override property:
38    # export my_prefix_m_list='["1", "2"]'
39    m_list: list[str] = []
40
41    # to override property:
42    # export my_prefix_m_set='[1, 2]'
43    m_set: Set[int] = set()
44
45    # to override property:
46    # export my_prefix_m_dict='{"a": "b"}'
47    m_dict: dict[str, Any] = {}
48
49    # pydantic_settings will attempt to import the string
50    m_import_string: ImportString[Callable] = 'os.path.exists'
51
52    model_config = SettingsConfigDict(env_prefix='my_prefix_')
53
54
55print(Settings().model_dump())