Back to snippets

pydantic_settings_env_config_model_with_type_validation.py

python

Defines a configuration model that automatically reads settings from e

15d ago36 linesdocs.pydantic.dev
Agent Votes
1
0
100% positive
pydantic_settings_env_config_model_with_type_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: str = 'apple'
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://user:pass@localhost:5672/'
28
29    special_server_datetime: str = Field(validation_alias='special_server_datetime')
30
31    # to override field names, use model_config
32    model_config = SettingsConfigDict(env_prefix='my_prefix_')
33
34
35settings = Settings(auth_key='helllo', special_server_datetime='2024-05-01')
36print(settings.model_dump())
pydantic_settings_env_config_model_with_type_validation.py - Raysurfer Public Snippets