python config_error ai_generated true

pydantic_core._pydantic_core.ValidationError: 1 个验证错误,字段 database_urls 输入应为有效列表 [type=list_type]

pydantic_core._pydantic_core.ValidationError: 1 validation error for AppSettings database_urls Input should be a valid list [type=list_type, input_value='["db1","db2"]', input_type=str]

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

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

版本兼容性

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

根因分析

pydantic-settings 默认将环境变量作为字符串解析。当列表类型字段从环境变量填充时,JSON 字符串不会自动解码,除非字段被标注为复杂解析。

English

pydantic-settings parses environment variables as strings by default. When a list-typed field is populated from an env var, the JSON string is not automatically decoded unless the field is annotated for complex parsing.

generic

解决方案

  1. 90% 成功率
    from pydantic_settings import BaseSettings, SettingsConfigDict
    from pydantic import field_validator
    import json
    
    class AppSettings(BaseSettings):
        model_config = SettingsConfigDict(env_file='.env')
        database_urls: list[str]
    
        @field_validator('database_urls', mode='before')
        @classmethod
        def parse_json(cls, v):
            if isinstance(v, str):
                return json.loads(v)
            return v
  2. 75% 成功率
    from pydantic_settings import BaseSettings, SettingsConfigDict
    from pydantic import Field
    
    class AppSettings(BaseSettings):
        database_urls: list[str] = Field(default_factory=list)

无效尝试

常见但无效的做法:

  1. 85% 失败

    These settings control None handling and variable naming, not JSON decoding of complex types.

  2. 70% 失败

    The validator receives the raw string before type coercion, so isinstance(v, list) is False and the error is re-raised.