python config_error ai_generated true

pydantic_settings.exceptions.SettingsError: 从 "EnvSettingsSource" 解析字段 "allowed_hosts" 的值时出错

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

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

其他格式: JSON · Markdown 中文 · English
80%修复率
84%置信度
0证据数
2024-06-30首次发现

版本兼容性

版本状态引入弃用备注
2.x active — — —

根因分析

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

English

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

解决方案

  1. 95% 成功率
    export ALLOWED_HOSTS='["a.com", "b.com"]'
  2. 80% 成功率
    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% 成功率
    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

无效尝试

常见但无效的做法:

  1. 75% 失败

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

  2. 90% 失败

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

  3. 85% 失败

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