python config_error ai_generated true

pydantic_settings.exceptions.SettingsError: error parsing value for field "allowed_hosts" from source "EnvSettingsSource"

ID: python/pydantic-settings-env-parse-error

Also available as: JSON · Markdown · 中文
80%Fix Rate
84%Confidence
0Evidence
2024-06-30First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
2.x active — — —

Root Cause

An environment variable holding a complex type (list, dict) could not be parsed because Pydantic Settings expects JSON for non-scalar types by default.

generic

中文

环境变量中存放的是复杂类型(列表、字典),但 Pydantic Settings 默认期望非标量类型为 JSON 格式,因此解析失败。

Workarounds

  1. 95% success
    export ALLOWED_HOSTS='["a.com", "b.com"]'
  2. 80% success
    from pydantic_settings import BaseSettings, SettingsConfigDict
    class S(BaseSettings):
        model_config = SettingsConfigDict(env_parse_none_str="null")
        allowed_hosts: list[str] = []
    # Set env var: ALLOWED_HOSTS=a.com,b.com and override the source
  3. 90% success
    from pydantic import field_validator
    class S(BaseSettings):
        allowed_hosts: list[str] = []
        @field_validator("allowed_hosts", mode="before")
        @classmethod
        def split(cls, v):
            if isinstance(v, str):
                return [x.strip() for x in v.split(",")]
            return v

Dead Ends

Common approaches that don't work:

  1. 75% fail

    Shell quoting affects the string delivered to the process but does not change the JSON parsing requirement.

  2. 90% fail

    Case sensitivity does not affect value parsing, only key matching.

  3. 85% fail

    Naming convention is irrelevant; the content format is the problem.