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

- **ID:** `python/pydantic-settings-env-parse-error`
- **领域:** python
- **类别:** config_error
- **验证级别:** ai_generated
- **修复率:** 80%

## 根因

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

## 版本兼容性

| 版本 | 状态 | 引入 | 弃用 |
|------|------|------|------|
| 2.x | active | — | — |

## 解决方案

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
   ```

## 无效尝试

- **** — Shell quoting affects the string delivered to the process but does not change the JSON parsing requirement. (75% 失败率)
- **** — Case sensitivity does not affect value parsing, only key matching. (90% 失败率)
- **** — Naming convention is irrelevant; the content format is the problem. (85% 失败率)
