You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

为何Settings类中使用SecretStr会触发ValidationError错误?

问题描述

我有一个存储Telegram Bot令牌的标准.env文件,内容示例如下:

BOT_TOKEN = <bot_token>

同时我有一个config_reader.py文件用于解析.env文件获取令牌,代码如下:

from pydantic_settings import BaseSettings, SettingsConfigDict
from pydantic import SecretStr


class Settings(BaseSettings):
    bot_token: SecretStr

    model_config = SettingsConfigDict(env_file='.env', env_file_encoding='utf-8')


config = Settings()

主文件bot.py的代码如下:

async def main():
    bot = Bot(token=config.bot_token.get_secret_value(), parse_mode="HTML")
    dp = Dispatcher()

    logging.basicConfig(filename="bot_logging.log", encoding="utf-8", 
                        format="%(asctime)s %(message)s", datefmt="%m/%d/%Y %H:%M:%S",
                        level=logging.INFO)
    
    dp.include_routers(messages.router, different_types.router)

    await bot.delete_webhook(drop_pending_updates=True)
    await dp.start_polling(bot)

启动主文件时出现如下错误:

__pydantic_self__.__pydantic_validator__.validate_python(data, self_instance=__pydantic_self__)
pydantic_core._pydantic_core.ValidationError: 1 validation error for Settings
bot_token
  Field required [type=missing, input_value={}, input_type=dict]

请问为何会出现该错误?

错误原因及解决办法

这个错误表明Pydantic无法从.env文件中读取到bot_token对应的字段值,常见原因及解决方式如下:

  • .env文件路径错误
    Pydantic默认从当前工作目录加载.env文件。如果config_reader.py与.env文件不在同一目录,或者启动脚本时的工作目录不是.env所在目录,就会导致文件无法被找到。可以改为使用绝对路径指定.env文件位置,或者确保启动脚本时的工作目录正确。
    示例(使用绝对路径):

    model_config = SettingsConfigDict(env_file='/绝对路径/到你的/.env', env_file_encoding='utf-8')
    
  • 环境变量名格式问题
    Pydantic默认将类中的蛇形字段名bot_token映射为大写的BOT_TOKEN环境变量名,但要注意.env文件中等号前后的空格可能会被解析为变量名或值的一部分。建议将.env中的内容改为无空格的格式:

    BOT_TOKEN=<bot_token>
    
  • Pydantic配置或版本问题
    检查pydantic-settings版本是否为最新稳定版,老旧版本可能存在配置解析的bug。另外,可确认model_config中的配置是否正确,比如是否开启了case_sensitive(默认关闭,不区分大小写,但保持变量名一致更稳妥)。

  • .env文件未被正确加载
    可以在config_reader.py中添加调试代码,验证.env文件是否存在:

    import os
    print(os.path.exists('.env'))  # 输出True表示文件存在,False则说明路径错误
    

内容的提问来源于stack exchange,提问作者Elijah Sokol

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.05 12:25:18