pydantic / pydantic-settings

Settings management using pydantic
https://docs.pydantic.dev/latest/usage/pydantic_settings/
MIT License
508 stars 50 forks source link

Problems with nested settings in pydantic-settings v2.2.1 #251

Closed MartiAndrew closed 4 months ago

MartiAndrew commented 4 months ago

Hello, please help me with issue:

Available:

pydantic v 2.6.3 pydantic-factories v 1.17.3 pydantic-settings v 2.2.1

script:

class WebSettings(BaseSettings):
    model_config = SettingsConfigDict(
        env_prefix=f"{ENV_PREFIX}WEB_",
        env_file=PROJECT_ROOT.joinpath(".env"),
        env_file_encoding="utf-8",
    )

    host: str = "127.0.0.1"
    port: int = 8000
    workers_count: int = 1

class SentrySettings(BaseSettings):

    model_config = SettingsConfigDict(
        env_prefix=f"{ENV_PREFIX}SENTRY_",
        env_file=PROJECT_ROOT.joinpath(".env"),
        env_file_encoding="utf-8",
    )

    dsn: str = ""
    traces_sample_rate: float = 0.05

class Settings(BaseSettings):

    model_config = SettingsConfigDict(
        env_prefix=ENV_PREFIX,
        env_file=PROJECT_ROOT.joinpath(".env"),
        env_file_encoding="utf-8"
    )

    web: WebSettings = WebSettings()

    sentry: SentrySettings = SentrySettings()

I set env_variables, but These variables were used in classes for which they were not intended. This behavior came as a surprise. When I run the project I get the error:

pydantic_core._pydantic_core.ValidationError: 7 validation errors for WebSettings
project_configs_enable
  Extra inputs are not permitted [type=extra_forbidden, input_value='0', input_type=str]
    For further information visit https://errors.pydantic.dev/2.6/v/extra_forbidden
project_logger_db_echo
  Extra inputs are not permitted [type=extra_forbidden, input_value='1', input_type=str]
    For further information visit https://errors.pydantic.dev/2.6/v/extra_forbidden
project_logger_log_in_one_line
  Extra inputs are not permitted [type=extra_forbidden, input_value='0', input_type=str]
    For further information visit https://errors.pydantic.dev/2.6/v/extra_forbidden
project_telemetry_endpoint
  Extra inputs are not permitted [type=extra_forbidden, input_value='http://localhost:4317', input_type=str]
    For further information visit https://errors.pydantic.dev/2.6/v/extra_forbidden
Atypical behavior after changing pydantic-settings version to 2.2.1 How to solve this problem? thank you in advance.
hramezani commented 4 months ago

It is related to this issue https://github.com/pydantic/pydantic-settings/issues/245 You can fix the problem by adding extra='ignore' config

MartiAndrew commented 4 months ago

Thank you very much Hasan, I almost reached this solution myself, but it was just a little bit short. Thanks for your work again.