如何为Pedantic BaseSettings自定义并暴露配置源?
让BaseSettings加载自定义RuntimeBaseSettingsSource的方法
要让你的自定义RuntimeBaseSettingsSource被BaseSettings加载,核心是通过重写settings_customise_sources方法将其注入到配置源列表中,具体有两种常用方式:
方式一:单个配置类中注入
直接在你的BaseSettings子类里重写settings_customise_sources方法,把自定义源加入到配置源序列中,同时可以控制它的优先级(顺序越靠后,优先级越高,会覆盖前面源的同名配置):
from pydantic_settings import BaseSettings, BaseSettingsSource # 你的已实现的自定义源 class RuntimeBaseSettingsSource(BaseSettingsSource): def get_field_value(self, field, field_name): # 实现运行时获取字段值的逻辑 pass def prepare_field_value(self, field_name, field_value, value_is_complex): # 实现字段值的预处理逻辑 pass def __call__(self): # 返回运行时配置的字典 return {"api_key": "runtime_key", "db_url": "runtime_db_url"} # 自定义配置类,注入运行时源 class MyAppSettings(BaseSettings): api_key: str db_url: str @classmethod def settings_customise_sources( cls, settings_cls, init_settings, env_settings, dotenv_settings, file_secret_settings, ): # 调整源的顺序,这里将运行时源放在环境变量之后、dotenv之前 return ( init_settings, env_settings, RuntimeBaseSettingsSource(settings_cls), dotenv_settings, file_secret_settings, ) # 测试加载 settings = MyAppSettings() print(settings.api_key) # 会优先取运行时源的值(如果存在)
方式二:创建通用基类供多配置类继承
如果你的项目中有多个配置类需要使用这个运行时源,可以先创建一个包含注入逻辑的基类,其他配置类直接继承即可:
# 创建通用基类 class RuntimeEnabledBaseSettings(BaseSettings): @classmethod def settings_customise_sources( cls, settings_cls, init_settings, env_settings, dotenv_settings, file_secret_settings, ): # 这里将运行时源放在最前面,优先级最高 return ( RuntimeBaseSettingsSource(settings_cls), init_settings, env_settings, dotenv_settings, file_secret_settings, ) # 业务配置类继承通用基类 class AuthSettings(RuntimeEnabledBaseSettings): jwt_secret: str token_expire_hours: int class DatabaseSettings(RuntimeEnabledBaseSettings): db_host: str db_port: int
关键注意事项
- 配置源顺序:
settings_customise_sources返回的元组顺序决定了配置的优先级,后面的源会覆盖前面源的同名配置项,根据你的业务需求调整位置即可。 - 自定义源的实现:确保
RuntimeBaseSettingsSource的__call__方法返回合法的配置字典,get_field_value和prepare_field_value方法正确处理字段的取值与转换逻辑,否则可能导致配置加载失败。
内容的提问来源于stack exchange,提问作者slayton
相关产品推荐
相关产品推荐

