python
config_error
ai_generated
true
pydantic_core._pydantic_core.ValidationError:1 个验证错误(Settings) database_url 字段必填 [type=missing, input_value={}, input_type=dict]
pydantic_core._pydantic_core.ValidationError: 1 validation error for Settings database_url Field required [type=missing, input_value={}, input_type=dict]
ID: python/pydantic-settings-env-not-loaded
80%修复率
86%置信度
0证据数
2024-09-27首次发现
版本兼容性
| 版本 | 状态 | 引入 | 弃用 | 备注 |
|---|---|---|---|---|
| 2.x | active | — | — | — |
根因分析
pydantic-settings 在实例化时读取环境变量;变量名大小写或前缀不匹配,或未加载 .env 文件。
English
pydantic-settings reads env vars at instantiation; the variable name case or prefix doesn't match, or .env file isn't loaded.
解决方案
-
95% 成功率
from pydantic_settings import BaseSettings, SettingsConfigDict class Settings(BaseSettings): model_config = SettingsConfigDict(env_file='.env', case_sensitive=False) database_url: str -
90% 成功率
export DATABASE_URL=postgres://... python -c 'import os; print(os.environ.get("DATABASE_URL"))'
无效尝试
常见但无效的做法:
-
45% 失败
Still requires the var to be present in os.environ at import time.
-
60% 失败
Defeats the purpose of env-driven config; secrets end up in source.
-
50% 失败
Runs after field resolution; too late for required-field errors.