跳到内容

Pydantic 设置

BaseSettings

BaseSettings(
    __pydantic_self__,
    _case_sensitive: bool | None = None,
    _nested_model_default_partial_update: (
        bool | None
    ) = None,
    _env_prefix: str | None = None,
    _env_file: DotenvType | None = ENV_FILE_SENTINEL,
    _env_file_encoding: str | None = None,
    _env_ignore_empty: bool | None = None,
    _env_nested_delimiter: str | None = None,
    _env_parse_none_str: str | None = None,
    _env_parse_enums: bool | None = None,
    _cli_prog_name: str | None = None,
    _cli_parse_args: (
        bool | list[str] | tuple[str, ...] | None
    ) = None,
    _cli_settings_source: (
        CliSettingsSource[Any] | None
    ) = None,
    _cli_parse_none_str: str | None = None,
    _cli_hide_none_type: bool | None = None,
    _cli_avoid_json: bool | None = None,
    _cli_enforce_required: bool | None = None,
    _cli_use_class_docs_for_groups: bool | None = None,
    _cli_exit_on_error: bool | None = None,
    _cli_prefix: str | None = None,
    _cli_flag_prefix_char: str | None = None,
    _cli_implicit_flags: bool | None = None,
    _cli_ignore_unknown_args: bool | None = None,
    _cli_kebab_case: bool | None = None,
    _secrets_dir: PathType | None = None,
    **values: Any
)

基类: BaseModel

设置的基类,允许通过环境变量覆盖值。

这在生产环境中对于您不希望保存在代码中的密钥非常有用,它可以很好地与 docker(-compose)、Heroku 和任何 12 要素应用设计配合使用。

所有以下属性都可以通过 model_config 设置。

参数

名称 类型 描述 默认值
_case_sensitive bool | None

环境变量和 CLI 变量名称是否应区分大小写读取。默认为 None

None
_nested_model_default_partial_update bool | None

是否允许对嵌套模型默认对象字段进行部分更新。默认为 False

None
_env_prefix str | None

所有环境变量的前缀。默认为 None

None
_env_file DotenvType | None

要从中加载设置值的 env 文件。默认为 Path(''),这意味着应使用 model_config['env_file'] 中的值。您也可以传递 None 以指示不应从 env 文件加载环境变量。

ENV_FILE_SENTINEL
_env_file_encoding str | None

env 文件的编码,例如 'latin-1'。默认为 None

None
_env_ignore_empty bool | None

忽略值为空字符串的环境变量。默认为 False

None
_env_nested_delimiter str | None

嵌套 env 值的分隔符。默认为 None

None
_env_parse_none_str str | None

应解析为 None 类型 (None) 的 env 字符串值(例如“null”、“void”、“None”等)。默认为 None 类型 (None),这意味着不应进行解析。

None
_env_parse_enums bool | None

将枚举字段名称解析为值。默认为 None.,这意味着不应进行解析。

None
_cli_prog_name str | None

CLI 程序名称,用于在帮助文本中显示。如果 _cli_parse_args 为 None,则默认为 None。否则,默认为 sys.argv[0]。

None
_cli_parse_args bool | list[str] | tuple[str, ...] | None

要解析的 CLI 参数列表。默认为 None。如果设置为 True,则默认为 sys.argv[1:]。

None
_cli_settings_source CliSettingsSource[Any] | None

使用用户定义的实例覆盖默认的 CLI 设置源。默认为 None。

None
_cli_parse_none_str str | None

应解析为 None 类型 (None) 的 CLI 字符串值(例如“null”、“void”、“None”等)。如果设置了 _env_parse_none_str 值,则默认为该值。否则,如果 _cli_avoid_json 为 False,则默认为“null”,如果 _cli_avoid_json 为 True,则默认为“None”。

None
_cli_hide_none_type bool | None

在 CLI 帮助文本中隐藏 None 值。默认为 False

None
_cli_avoid_json bool | None

避免在 CLI 帮助文本中使用复杂的 JSON 对象。默认为 False

None
_cli_enforce_required bool | None

在 CLI 强制执行必填字段。默认为 False

None
_cli_use_class_docs_for_groups bool | None

在 CLI 组帮助文本中使用类文档字符串而不是字段描述。默认为 False

None
_cli_exit_on_error bool | None

确定当发生错误时内部解析器是否退出并显示错误信息。默认为 True

None
_cli_prefix str | None

根解析器命令行参数前缀。默认为 ""。

None
_cli_flag_prefix_char str | None

用于 CLI 可选参数的标志前缀字符。默认为 '-'。

None
_cli_implicit_flags bool | None

bool 字段是否应隐式转换为 CLI 布尔标志。(例如 --flag, --no-flag)。默认为 False

None
_cli_ignore_unknown_args bool | None

是否忽略未知的 CLI 参数,仅解析已知的参数。默认为 False

None
_cli_kebab_case bool | None

CLI 参数使用 kebab case。默认为 False

None
_secrets_dir PathType | None

密钥文件目录或目录序列。默认为 None

None
源代码位于 .venv/lib/python3.12/site-packages/pydantic_settings/main.py
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
def __init__(
    __pydantic_self__,
    _case_sensitive: bool | None = None,
    _nested_model_default_partial_update: bool | None = None,
    _env_prefix: str | None = None,
    _env_file: DotenvType | None = ENV_FILE_SENTINEL,
    _env_file_encoding: str | None = None,
    _env_ignore_empty: bool | None = None,
    _env_nested_delimiter: str | None = None,
    _env_parse_none_str: str | None = None,
    _env_parse_enums: bool | None = None,
    _cli_prog_name: str | None = None,
    _cli_parse_args: bool | list[str] | tuple[str, ...] | None = None,
    _cli_settings_source: CliSettingsSource[Any] | None = None,
    _cli_parse_none_str: str | None = None,
    _cli_hide_none_type: bool | None = None,
    _cli_avoid_json: bool | None = None,
    _cli_enforce_required: bool | None = None,
    _cli_use_class_docs_for_groups: bool | None = None,
    _cli_exit_on_error: bool | None = None,
    _cli_prefix: str | None = None,
    _cli_flag_prefix_char: str | None = None,
    _cli_implicit_flags: bool | None = None,
    _cli_ignore_unknown_args: bool | None = None,
    _cli_kebab_case: bool | None = None,
    _secrets_dir: PathType | None = None,
    **values: Any,
) -> None:
    # Uses something other than `self` the first arg to allow "self" as a settable attribute
    super().__init__(
        **__pydantic_self__._settings_build_values(
            values,
            _case_sensitive=_case_sensitive,
            _nested_model_default_partial_update=_nested_model_default_partial_update,
            _env_prefix=_env_prefix,
            _env_file=_env_file,
            _env_file_encoding=_env_file_encoding,
            _env_ignore_empty=_env_ignore_empty,
            _env_nested_delimiter=_env_nested_delimiter,
            _env_parse_none_str=_env_parse_none_str,
            _env_parse_enums=_env_parse_enums,
            _cli_prog_name=_cli_prog_name,
            _cli_parse_args=_cli_parse_args,
            _cli_settings_source=_cli_settings_source,
            _cli_parse_none_str=_cli_parse_none_str,
            _cli_hide_none_type=_cli_hide_none_type,
            _cli_avoid_json=_cli_avoid_json,
            _cli_enforce_required=_cli_enforce_required,
            _cli_use_class_docs_for_groups=_cli_use_class_docs_for_groups,
            _cli_exit_on_error=_cli_exit_on_error,
            _cli_prefix=_cli_prefix,
            _cli_flag_prefix_char=_cli_flag_prefix_char,
            _cli_implicit_flags=_cli_implicit_flags,
            _cli_ignore_unknown_args=_cli_ignore_unknown_args,
            _cli_kebab_case=_cli_kebab_case,
            _secrets_dir=_secrets_dir,
        )
    )

settings_customise_sources classmethod

settings_customise_sources(
    settings_cls: type[BaseSettings],
    init_settings: PydanticBaseSettingsSource,
    env_settings: PydanticBaseSettingsSource,
    dotenv_settings: PydanticBaseSettingsSource,
    file_secret_settings: PydanticBaseSettingsSource,
) -> tuple[PydanticBaseSettingsSource, ...]

定义加载设置值的来源及其顺序。

参数

名称 类型 描述 默认值
settings_cls type[BaseSettings]

Settings 类。

required
init_settings PydanticBaseSettingsSource

InitSettingsSource 实例。

required
env_settings PydanticBaseSettingsSource

EnvSettingsSource 实例。

required
dotenv_settings PydanticBaseSettingsSource

DotEnvSettingsSource 实例。

required
file_secret_settings PydanticBaseSettingsSource

SecretsSettingsSource 实例。

required

返回

类型 描述
tuple[PydanticBaseSettingsSource, ...]

包含加载设置值的来源及其顺序的元组。

源代码位于 .venv/lib/python3.12/site-packages/pydantic_settings/main.py
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
@classmethod
def settings_customise_sources(
    cls,
    settings_cls: type[BaseSettings],
    init_settings: PydanticBaseSettingsSource,
    env_settings: PydanticBaseSettingsSource,
    dotenv_settings: PydanticBaseSettingsSource,
    file_secret_settings: PydanticBaseSettingsSource,
) -> tuple[PydanticBaseSettingsSource, ...]:
    """
    Define the sources and their order for loading the settings values.

    Args:
        settings_cls: The Settings class.
        init_settings: The `InitSettingsSource` instance.
        env_settings: The `EnvSettingsSource` instance.
        dotenv_settings: The `DotEnvSettingsSource` instance.
        file_secret_settings: The `SecretsSettingsSource` instance.

    Returns:
        A tuple containing the sources and their order for loading the settings values.
    """
    return init_settings, env_settings, dotenv_settings, file_secret_settings

CliApp

一个实用程序类,用于将 Pydantic BaseSettingsBaseModelpydantic.dataclasses.dataclass 作为 CLI 应用程序运行。

run staticmethod

run(
    model_cls: type[T],
    cli_args: (
        list[str]
        | Namespace
        | SimpleNamespace
        | dict[str, Any]
        | None
    ) = None,
    cli_settings_source: (
        CliSettingsSource[Any] | None
    ) = None,
    cli_exit_on_error: bool | None = None,
    cli_cmd_method_name: str = "cli_cmd",
    **model_init_data: Any
) -> T

将 Pydantic BaseSettingsBaseModelpydantic.dataclasses.dataclass 作为 CLI 应用程序运行。将模型作为 CLI 应用程序运行需要模型类中定义 cli_cmd 方法。

参数

名称 类型 描述 默认值
model_cls type[T]

要作为 CLI 应用程序运行的模型类。

required
cli_args list[str] | Namespace | SimpleNamespace | dict[str, Any] | None

要解析的 CLI 参数列表。如果指定了 cli_settings_source,则也可以是预解析的 CLI 参数的命名空间或字典。默认为 sys.argv[1:]

None
cli_settings_source CliSettingsSource[Any] | None

使用用户定义的实例覆盖默认的 CLI 设置源。默认为 None

None
cli_exit_on_error bool | None

确定此函数是否在错误时退出。如果模型是 BaseSettings 的子类,则默认为 BaseSettings cli_exit_on_error 值。否则,默认为 True

None
cli_cmd_method_name str

要运行的 CLI 命令方法名称。默认为 "cli_cmd"。

'cli_cmd'
model_init_data Any

模型初始化数据。

{}

返回

类型 描述
T

运行后的模型实例。

引发

类型 描述
SettingsError

如果 model_cls 不是 BaseModelpydantic.dataclasses.dataclass 的子类。

SettingsError

如果 model_cls 没有定义 cli_cmd 入口点。

源代码位于 .venv/lib/python3.12/site-packages/pydantic_settings/main.py
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
@staticmethod
def run(
    model_cls: type[T],
    cli_args: list[str] | Namespace | SimpleNamespace | dict[str, Any] | None = None,
    cli_settings_source: CliSettingsSource[Any] | None = None,
    cli_exit_on_error: bool | None = None,
    cli_cmd_method_name: str = 'cli_cmd',
    **model_init_data: Any,
) -> T:
    """
    Runs a Pydantic `BaseSettings`, `BaseModel`, or `pydantic.dataclasses.dataclass` as a CLI application.
    Running a model as a CLI application requires the `cli_cmd` method to be defined in the model class.

    Args:
        model_cls: The model class to run as a CLI application.
        cli_args: The list of CLI arguments to parse. If `cli_settings_source` is specified, this may
            also be a namespace or dictionary of pre-parsed CLI arguments. Defaults to `sys.argv[1:]`.
        cli_settings_source: Override the default CLI settings source with a user defined instance.
            Defaults to `None`.
        cli_exit_on_error: Determines whether this function exits on error. If model is subclass of
            `BaseSettings`, defaults to BaseSettings `cli_exit_on_error` value. Otherwise, defaults to
            `True`.
        cli_cmd_method_name: The CLI command method name to run. Defaults to "cli_cmd".
        model_init_data: The model init data.

    Returns:
        The ran instance of model.

    Raises:
        SettingsError: If model_cls is not subclass of `BaseModel` or `pydantic.dataclasses.dataclass`.
        SettingsError: If model_cls does not have a `cli_cmd` entrypoint defined.
    """

    if not (is_pydantic_dataclass(model_cls) or is_model_class(model_cls)):
        raise SettingsError(
            f'Error: {model_cls.__name__} is not subclass of BaseModel or pydantic.dataclasses.dataclass'
        )

    cli_settings = None
    cli_parse_args = True if cli_args is None else cli_args
    if cli_settings_source is not None:
        if isinstance(cli_parse_args, (Namespace, SimpleNamespace, dict)):
            cli_settings = cli_settings_source(parsed_args=cli_parse_args)
        else:
            cli_settings = cli_settings_source(args=cli_parse_args)
    elif isinstance(cli_parse_args, (Namespace, SimpleNamespace, dict)):
        raise SettingsError('Error: `cli_args` must be list[str] or None when `cli_settings_source` is not used')

    model_init_data['_cli_parse_args'] = cli_parse_args
    model_init_data['_cli_exit_on_error'] = cli_exit_on_error
    model_init_data['_cli_settings_source'] = cli_settings
    if not issubclass(model_cls, BaseSettings):

        class CliAppBaseSettings(BaseSettings, model_cls):  # type: ignore
            model_config = SettingsConfigDict(
                nested_model_default_partial_update=True,
                case_sensitive=True,
                cli_hide_none_type=True,
                cli_avoid_json=True,
                cli_enforce_required=True,
                cli_implicit_flags=True,
                cli_kebab_case=True,
            )

        model = CliAppBaseSettings(**model_init_data)
        model_init_data = {}
        for field_name, field_info in model.model_fields.items():
            model_init_data[_field_name_for_signature(field_name, field_info)] = getattr(model, field_name)

    return CliApp._run_cli_cmd(model_cls(**model_init_data), cli_cmd_method_name, is_required=False)

run_subcommand staticmethod

run_subcommand(
    model: PydanticModel,
    cli_exit_on_error: bool | None = None,
    cli_cmd_method_name: str = "cli_cmd",
) -> PydanticModel

运行模型子命令。运行模型子命令需要在嵌套模型子命令类中定义 cli_cmd 方法。

参数

名称 类型 描述 默认值
model PydanticModel

从中运行子命令的模型。

required
cli_exit_on_error bool | None

确定如果未找到子命令,此函数是否退出并显示错误。如果设置了 model_config cli_exit_on_error 值,则默认为该值。否则,默认为 True

None
cli_cmd_method_name str

要运行的 CLI 命令方法名称。默认为 "cli_cmd"。

'cli_cmd'

返回

类型 描述
PydanticModel

运行后的子命令模型。

引发

类型 描述
SystemExit

当未找到子命令且 cli_exit_on_error=True(默认值)时。

SettingsError

当未找到子命令且 cli_exit_on_error=False 时。

源代码位于 .venv/lib/python3.12/site-packages/pydantic_settings/main.py
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
@staticmethod
def run_subcommand(
    model: PydanticModel, cli_exit_on_error: bool | None = None, cli_cmd_method_name: str = 'cli_cmd'
) -> PydanticModel:
    """
    Runs the model subcommand. Running a model subcommand requires the `cli_cmd` method to be defined in
    the nested model subcommand class.

    Args:
        model: The model to run the subcommand from.
        cli_exit_on_error: Determines whether this function exits with error if no subcommand is found.
            Defaults to model_config `cli_exit_on_error` value if set. Otherwise, defaults to `True`.
        cli_cmd_method_name: The CLI command method name to run. Defaults to "cli_cmd".

    Returns:
        The ran subcommand model.

    Raises:
        SystemExit: When no subcommand is found and cli_exit_on_error=`True` (the default).
        SettingsError: When no subcommand is found and cli_exit_on_error=`False`.
    """

    subcommand = get_subcommand(model, is_required=True, cli_exit_on_error=cli_exit_on_error)
    return CliApp._run_cli_cmd(subcommand, cli_cmd_method_name, is_required=True)

SettingsConfigDict

基类: ConfigDict

pyproject_toml_depth instance-attribute

pyproject_toml_depth: int

从当前工作目录向上尝试查找 pyproject.toml 文件的层数。

仅当在当前工作目录中未找到 pyproject.toml 文件时才使用此设置。

pyproject_toml_table_header instance-attribute

pyproject_toml_table_header: tuple[str, ...]

pyproject.toml 文件中 TOML 表的标头,用于填充变量。这以 tuple[str, ...] 而不是 str 的形式提供,以适应包含 . 的标头。

例如,toml_table_header = ("tool", "my.tool", "foo") 可用于从标头为 [tool."my.tool".foo] 的表中填充变量值。

要使用根表,请排除此配置设置或提供空元组。

CliSettingsSource

CliSettingsSource(
    settings_cls: type[BaseSettings],
    cli_prog_name: str | None = None,
    cli_parse_args: (
        bool | list[str] | tuple[str, ...] | None
    ) = None,
    cli_parse_none_str: str | None = None,
    cli_hide_none_type: bool | None = None,
    cli_avoid_json: bool | None = None,
    cli_enforce_required: bool | None = None,
    cli_use_class_docs_for_groups: bool | None = None,
    cli_exit_on_error: bool | None = None,
    cli_prefix: str | None = None,
    cli_flag_prefix_char: str | None = None,
    cli_implicit_flags: bool | None = None,
    cli_ignore_unknown_args: bool | None = None,
    cli_kebab_case: bool | None = None,
    case_sensitive: bool | None = True,
    root_parser: Any = None,
    parse_args_method: Callable[..., Any] | None = None,
    add_argument_method: (
        Callable[..., Any] | None
    ) = add_argument,
    add_argument_group_method: (
        Callable[..., Any] | None
    ) = add_argument_group,
    add_parser_method: (
        Callable[..., Any] | None
    ) = add_parser,
    add_subparsers_method: (
        Callable[..., Any] | None
    ) = add_subparsers,
    formatter_class: Any = RawDescriptionHelpFormatter,
)

基类: EnvSettingsSource, Generic[T]

用于从 CLI 加载设置值的源类。

注意

CliSettingsSource 通过使用解析器方法将 settings_cls 字段作为命令行参数添加,从而与 root_parser 对象连接。 CliSettingsSource 内部解析器表示基于 argparse 解析库,因此,要求解析器方法支持与其 argparse 库对应项相同的属性。

参数

名称 类型 描述 默认值
cli_prog_name str | None

CLI 程序名称,用于在帮助文本中显示。如果 cli_parse_args 为 None,则默认为 None。否则,默认为 sys.argv[0]。

None
cli_parse_args bool | list[str] | tuple[str, ...] | None

要解析的 CLI 参数列表。默认为 None。如果设置为 True,则默认为 sys.argv[1:]。

None
cli_parse_none_str str | None

应解析为 None 类型 (None) 的 CLI 字符串值(例如“null”、“void”、“None”等)。如果 cli_avoid_json 为 False,则默认为“null”,如果 cli_avoid_json 为 True,则默认为“None”。

None
cli_hide_none_type bool | None

在 CLI 帮助文本中隐藏 None 值。默认为 False

None
cli_avoid_json bool | None

避免在 CLI 帮助文本中使用复杂的 JSON 对象。默认为 False

None
cli_enforce_required bool | None

在 CLI 强制执行必填字段。默认为 False

None
cli_use_class_docs_for_groups bool | None

在 CLI 组帮助文本中使用类文档字符串而不是字段描述。默认为 False

None
cli_exit_on_error bool | None

确定当发生错误时内部解析器是否退出并显示错误信息。默认为 True

None
cli_prefix str | None

在根解析器下添加的命令行参数的前缀。默认为 ""。

None
cli_flag_prefix_char str | None

用于 CLI 可选参数的标志前缀字符。默认为 '-'。

None
cli_implicit_flags bool | None

bool 字段是否应隐式转换为 CLI 布尔标志。(例如 --flag, --no-flag)。默认为 False

None
cli_ignore_unknown_args bool | None

是否忽略未知的 CLI 参数,仅解析已知的参数。默认为 False

None
cli_kebab_case bool | None

CLI 参数使用 kebab case。默认为 False

None
case_sensitive bool | None

CLI "--arg" 名称是否应区分大小写读取。默认为 True。注意:不区分大小写的匹配仅在内部根解析器上受支持,不适用于 CLI 子命令。

True
root_parser Any

根解析器对象。

None
parse_args_method Callable[..., Any] | None

根解析器 parse args 方法。默认为 argparse.ArgumentParser.parse_args

None
add_argument_method Callable[..., Any] | None

根解析器 add argument 方法。默认为 argparse.ArgumentParser.add_argument

add_argument
add_argument_group_method Callable[..., Any] | None

根解析器 add argument group 方法。默认为 argparse.ArgumentParser.add_argument_group

add_argument_group
add_parser_method Callable[..., Any] | None

根解析器添加新解析器(子命令)方法。默认为 argparse._SubParsersAction.add_parser

add_parser
add_subparsers_method Callable[..., Any] | None

根解析器添加子解析器(子命令)方法。默认为 argparse.ArgumentParser.add_subparsers

add_subparsers
formatter_class Any

用于自定义根解析器帮助文本的类。默认为 argparse.RawDescriptionHelpFormatter

RawDescriptionHelpFormatter
源代码位于 .venv/lib/python3.12/site-packages/pydantic_settings/sources.py
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
def __init__(
    self,
    settings_cls: type[BaseSettings],
    cli_prog_name: str | None = None,
    cli_parse_args: bool | list[str] | tuple[str, ...] | None = None,
    cli_parse_none_str: str | None = None,
    cli_hide_none_type: bool | None = None,
    cli_avoid_json: bool | None = None,
    cli_enforce_required: bool | None = None,
    cli_use_class_docs_for_groups: bool | None = None,
    cli_exit_on_error: bool | None = None,
    cli_prefix: str | None = None,
    cli_flag_prefix_char: str | None = None,
    cli_implicit_flags: bool | None = None,
    cli_ignore_unknown_args: bool | None = None,
    cli_kebab_case: bool | None = None,
    case_sensitive: bool | None = True,
    root_parser: Any = None,
    parse_args_method: Callable[..., Any] | None = None,
    add_argument_method: Callable[..., Any] | None = ArgumentParser.add_argument,
    add_argument_group_method: Callable[..., Any] | None = ArgumentParser.add_argument_group,
    add_parser_method: Callable[..., Any] | None = _SubParsersAction.add_parser,
    add_subparsers_method: Callable[..., Any] | None = ArgumentParser.add_subparsers,
    formatter_class: Any = RawDescriptionHelpFormatter,
) -> None:
    self.cli_prog_name = (
        cli_prog_name if cli_prog_name is not None else settings_cls.model_config.get('cli_prog_name', sys.argv[0])
    )
    self.cli_hide_none_type = (
        cli_hide_none_type
        if cli_hide_none_type is not None
        else settings_cls.model_config.get('cli_hide_none_type', False)
    )
    self.cli_avoid_json = (
        cli_avoid_json if cli_avoid_json is not None else settings_cls.model_config.get('cli_avoid_json', False)
    )
    if not cli_parse_none_str:
        cli_parse_none_str = 'None' if self.cli_avoid_json is True else 'null'
    self.cli_parse_none_str = cli_parse_none_str
    self.cli_enforce_required = (
        cli_enforce_required
        if cli_enforce_required is not None
        else settings_cls.model_config.get('cli_enforce_required', False)
    )
    self.cli_use_class_docs_for_groups = (
        cli_use_class_docs_for_groups
        if cli_use_class_docs_for_groups is not None
        else settings_cls.model_config.get('cli_use_class_docs_for_groups', False)
    )
    self.cli_exit_on_error = (
        cli_exit_on_error
        if cli_exit_on_error is not None
        else settings_cls.model_config.get('cli_exit_on_error', True)
    )
    self.cli_prefix = cli_prefix if cli_prefix is not None else settings_cls.model_config.get('cli_prefix', '')
    self.cli_flag_prefix_char = (
        cli_flag_prefix_char
        if cli_flag_prefix_char is not None
        else settings_cls.model_config.get('cli_flag_prefix_char', '-')
    )
    self._cli_flag_prefix = self.cli_flag_prefix_char * 2
    if self.cli_prefix:
        if cli_prefix.startswith('.') or cli_prefix.endswith('.') or not cli_prefix.replace('.', '').isidentifier():  # type: ignore
            raise SettingsError(f'CLI settings source prefix is invalid: {cli_prefix}')
        self.cli_prefix += '.'
    self.cli_implicit_flags = (
        cli_implicit_flags
        if cli_implicit_flags is not None
        else settings_cls.model_config.get('cli_implicit_flags', False)
    )
    self.cli_ignore_unknown_args = (
        cli_ignore_unknown_args
        if cli_ignore_unknown_args is not None
        else settings_cls.model_config.get('cli_ignore_unknown_args', False)
    )
    self.cli_kebab_case = (
        cli_kebab_case if cli_kebab_case is not None else settings_cls.model_config.get('cli_kebab_case', False)
    )

    case_sensitive = case_sensitive if case_sensitive is not None else True
    if not case_sensitive and root_parser is not None:
        raise SettingsError('Case-insensitive matching is only supported on the internal root parser')

    super().__init__(
        settings_cls,
        env_nested_delimiter='.',
        env_parse_none_str=self.cli_parse_none_str,
        env_parse_enums=True,
        env_prefix=self.cli_prefix,
        case_sensitive=case_sensitive,
    )

    root_parser = (
        _CliInternalArgParser(
            cli_exit_on_error=self.cli_exit_on_error,
            prog=self.cli_prog_name,
            description=None if settings_cls.__doc__ is None else dedent(settings_cls.__doc__),
            formatter_class=formatter_class,
            prefix_chars=self.cli_flag_prefix_char,
            allow_abbrev=False,
        )
        if root_parser is None
        else root_parser
    )
    self._connect_root_parser(
        root_parser=root_parser,
        parse_args_method=parse_args_method,
        add_argument_method=add_argument_method,
        add_argument_group_method=add_argument_group_method,
        add_parser_method=add_parser_method,
        add_subparsers_method=add_subparsers_method,
        formatter_class=formatter_class,
    )

    if cli_parse_args not in (None, False):
        if cli_parse_args is True:
            cli_parse_args = sys.argv[1:]
        elif not isinstance(cli_parse_args, (list, tuple)):
            raise SettingsError(
                f'cli_parse_args must be List[str] or Tuple[str, ...], recieved {type(cli_parse_args)}'
            )
        self._load_env_vars(parsed_args=self._parse_args(self.root_parser, cli_parse_args))

root_parser property

root_parser: T

连接的根解析器实例。

DotEnvSettingsSource

DotEnvSettingsSource(
    settings_cls: type[BaseSettings],
    env_file: DotenvType | None = ENV_FILE_SENTINEL,
    env_file_encoding: str | None = None,
    case_sensitive: bool | None = None,
    env_prefix: str | None = None,
    env_nested_delimiter: str | None = None,
    env_ignore_empty: bool | None = None,
    env_parse_none_str: str | None = None,
    env_parse_enums: bool | None = None,
)

基类: EnvSettingsSource

用于从 env 文件加载设置值的源类。

源代码位于 .venv/lib/python3.12/site-packages/pydantic_settings/sources.py
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
def __init__(
    self,
    settings_cls: type[BaseSettings],
    env_file: DotenvType | None = ENV_FILE_SENTINEL,
    env_file_encoding: str | None = None,
    case_sensitive: bool | None = None,
    env_prefix: str | None = None,
    env_nested_delimiter: str | None = None,
    env_ignore_empty: bool | None = None,
    env_parse_none_str: str | None = None,
    env_parse_enums: bool | None = None,
) -> None:
    self.env_file = env_file if env_file != ENV_FILE_SENTINEL else settings_cls.model_config.get('env_file')
    self.env_file_encoding = (
        env_file_encoding if env_file_encoding is not None else settings_cls.model_config.get('env_file_encoding')
    )
    super().__init__(
        settings_cls,
        case_sensitive,
        env_prefix,
        env_nested_delimiter,
        env_ignore_empty,
        env_parse_none_str,
        env_parse_enums,
    )

EnvSettingsSource

EnvSettingsSource(
    settings_cls: type[BaseSettings],
    case_sensitive: bool | None = None,
    env_prefix: str | None = None,
    env_nested_delimiter: str | None = None,
    env_ignore_empty: bool | None = None,
    env_parse_none_str: str | None = None,
    env_parse_enums: bool | None = None,
)

基类: PydanticBaseEnvSettingsSource

用于从环境变量加载设置值的源类。

源代码位于 .venv/lib/python3.12/site-packages/pydantic_settings/sources.py
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
def __init__(
    self,
    settings_cls: type[BaseSettings],
    case_sensitive: bool | None = None,
    env_prefix: str | None = None,
    env_nested_delimiter: str | None = None,
    env_ignore_empty: bool | None = None,
    env_parse_none_str: str | None = None,
    env_parse_enums: bool | None = None,
) -> None:
    super().__init__(
        settings_cls, case_sensitive, env_prefix, env_ignore_empty, env_parse_none_str, env_parse_enums
    )
    self.env_nested_delimiter = (
        env_nested_delimiter if env_nested_delimiter is not None else self.config.get('env_nested_delimiter')
    )
    self.env_prefix_len = len(self.env_prefix)

    self.env_vars = self._load_env_vars()

get_field_value

get_field_value(
    field: FieldInfo, field_name: str
) -> tuple[Any, str, bool]

从环境变量获取字段的值,以及一个标志,用于确定值是否复杂。

参数

名称 类型 描述 默认值
field FieldInfo

字段。

required
field_name str

字段名称。

required

返回

类型 描述
tuple[Any, str, bool]

一个元组,包含值(如果未找到则为 None)、键以及一个标志,用于确定值是否复杂。

源代码位于 .venv/lib/python3.12/site-packages/pydantic_settings/sources.py
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
def get_field_value(self, field: FieldInfo, field_name: str) -> tuple[Any, str, bool]:
    """
    Gets the value for field from environment variables and a flag to determine whether value is complex.

    Args:
        field: The field.
        field_name: The field name.

    Returns:
        A tuple that contains the value (`None` if not found), key, and
            a flag to determine whether value is complex.
    """

    env_val: str | None = None
    for field_key, env_name, value_is_complex in self._extract_field_info(field, field_name):
        env_val = self.env_vars.get(env_name)
        if env_val is not None:
            break

    return env_val, field_key, value_is_complex

prepare_field_value

prepare_field_value(
    field_name: str,
    field: FieldInfo,
    value: Any,
    value_is_complex: bool,
) -> Any

准备字段的值。

  • 提取嵌套字段的值。
  • 将值反序列化为复杂字段的 Python 对象。

参数

名称 类型 描述 默认值
field FieldInfo

字段。

required
field_name str

字段名称。

required

返回

类型 描述
Any

一个元组,包含字段的准备好的值。

引发

类型 描述
ValuesError

当反序列化复杂字段的值时发生错误。

源代码位于 .venv/lib/python3.12/site-packages/pydantic_settings/sources.py
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
def prepare_field_value(self, field_name: str, field: FieldInfo, value: Any, value_is_complex: bool) -> Any:
    """
    Prepare value for the field.

    * Extract value for nested field.
    * Deserialize value to python object for complex field.

    Args:
        field: The field.
        field_name: The field name.

    Returns:
        A tuple contains prepared value for the field.

    Raises:
        ValuesError: When There is an error in deserializing value for complex field.
    """
    is_complex, allow_parse_failure = self._field_is_complex(field)
    if self.env_parse_enums:
        enum_val = _annotation_enum_name_to_val(field.annotation, value)
        value = value if enum_val is None else enum_val

    if is_complex or value_is_complex:
        if isinstance(value, EnvNoneType):
            return value
        elif value is None:
            # field is complex but no value found so far, try explode_env_vars
            env_val_built = self.explode_env_vars(field_name, field, self.env_vars)
            if env_val_built:
                return env_val_built
        else:
            # field is complex and there's a value, decode that as JSON, then add explode_env_vars
            try:
                value = self.decode_complex_value(field_name, field, value)
            except ValueError as e:
                if not allow_parse_failure:
                    raise e

            if isinstance(value, dict):
                return deep_update(value, self.explode_env_vars(field_name, field, self.env_vars))
            else:
                return value
    elif value is not None:
        # simplest case, field is not complex, we only need to add the value if it was found
        return value

next_field

next_field(
    field: FieldInfo | Any | None,
    key: str,
    case_sensitive: bool | None = None,
) -> FieldInfo | None

通过键(env 名称)在子模型中查找字段

通过以下模型

```py
class SubSubModel(BaseSettings):
    dvals: Dict

class SubModel(BaseSettings):
    vals: list[str]
    sub_sub_model: SubSubModel

class Cfg(BaseSettings):
    sub_model: SubModel
```
然后

next_field(sub_model, 'vals') 返回 SubModel 类的 vals 字段 next_field(sub_model, 'sub_sub_model') 返回 SubModel 类的 sub_sub_model 字段

参数

名称 类型 描述 默认值
field FieldInfo | Any | None

字段。

required
key str

键(env 名称)。

required
case_sensitive bool | None

是否区分大小写搜索键。

None

返回

类型 描述
FieldInfo | None

如果找到下一个字段,则为字段,否则为 None

源代码位于 .venv/lib/python3.12/site-packages/pydantic_settings/sources.py
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
def next_field(
    self, field: FieldInfo | Any | None, key: str, case_sensitive: bool | None = None
) -> FieldInfo | None:
    """
    Find the field in a sub model by key(env name)

    By having the following models:

        ```py
        class SubSubModel(BaseSettings):
            dvals: Dict

        class SubModel(BaseSettings):
            vals: list[str]
            sub_sub_model: SubSubModel

        class Cfg(BaseSettings):
            sub_model: SubModel
        ```

    Then:
        next_field(sub_model, 'vals') Returns the `vals` field of `SubModel` class
        next_field(sub_model, 'sub_sub_model') Returns `sub_sub_model` field of `SubModel` class

    Args:
        field: The field.
        key: The key (env name).
        case_sensitive: Whether to search for key case sensitively.

    Returns:
        Field if it finds the next field otherwise `None`.
    """
    if not field:
        return None

    annotation = field.annotation if isinstance(field, FieldInfo) else field
    if origin_is_union(get_origin(annotation)) or isinstance(annotation, WithArgsTypes):
        for type_ in get_args(annotation):
            type_has_key = self.next_field(type_, key, case_sensitive)
            if type_has_key:
                return type_has_key
    elif is_model_class(annotation) or is_pydantic_dataclass(annotation):
        fields = _get_model_fields(annotation)
        # `case_sensitive is None` is here to be compatible with the old behavior.
        # Has to be removed in V3.
        for field_name, f in fields.items():
            for _, env_name, _ in self._extract_field_info(f, field_name):
                if case_sensitive is None or case_sensitive:
                    if field_name == key or env_name == key:
                        return f
                elif field_name.lower() == key.lower() or env_name.lower() == key.lower():
                    return f
    return None

explode_env_vars

explode_env_vars(
    field_name: str,
    field: FieldInfo,
    env_vars: Mapping[str, str | None],
) -> dict[str, Any]

处理 env_vars 并将包含 env_nested_delimiter 的键的值提取到嵌套字典中。

这应用于单个字段,因此按 env_var 前缀进行筛选。

参数

名称 类型 描述 默认值
field_name str

字段名称。

required
field FieldInfo

字段。

required
env_vars Mapping[str, str | None]

环境变量。

required

返回

类型 描述
dict[str, Any]

一个字典,包含从嵌套 env 值中提取的值。

源代码位于 .venv/lib/python3.12/site-packages/pydantic_settings/sources.py
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
def explode_env_vars(self, field_name: str, field: FieldInfo, env_vars: Mapping[str, str | None]) -> dict[str, Any]:
    """
    Process env_vars and extract the values of keys containing env_nested_delimiter into nested dictionaries.

    This is applied to a single field, hence filtering by env_var prefix.

    Args:
        field_name: The field name.
        field: The field.
        env_vars: Environment variables.

    Returns:
        A dictionary contains extracted values from nested env values.
    """
    is_dict = lenient_issubclass(get_origin(field.annotation), dict)

    prefixes = [
        f'{env_name}{self.env_nested_delimiter}' for _, env_name, _ in self._extract_field_info(field, field_name)
    ]
    result: dict[str, Any] = {}
    for env_name, env_val in env_vars.items():
        if not any(env_name.startswith(prefix) for prefix in prefixes):
            continue
        # we remove the prefix before splitting in case the prefix has characters in common with the delimiter
        env_name_without_prefix = env_name[self.env_prefix_len :]
        _, *keys, last_key = env_name_without_prefix.split(self.env_nested_delimiter)
        env_var = result
        target_field: FieldInfo | None = field
        for key in keys:
            target_field = self.next_field(target_field, key, self.case_sensitive)
            if isinstance(env_var, dict):
                env_var = env_var.setdefault(key, {})

        # get proper field with last_key
        target_field = self.next_field(target_field, last_key, self.case_sensitive)

        # check if env_val maps to a complex field and if so, parse the env_val
        if (target_field or is_dict) and env_val:
            if target_field:
                is_complex, allow_json_failure = self._field_is_complex(target_field)
            else:
                # nested field type is dict
                is_complex, allow_json_failure = True, True
            if is_complex:
                try:
                    env_val = self.decode_complex_value(last_key, target_field, env_val)  # type: ignore
                except ValueError as e:
                    if not allow_json_failure:
                        raise e
        if isinstance(env_var, dict):
            if last_key not in env_var or not isinstance(env_val, EnvNoneType) or env_var[last_key] == {}:
                env_var[last_key] = env_val

    return result

ForceDecode

强制解码字段值的注解。

InitSettingsSource

InitSettingsSource(
    settings_cls: type[BaseSettings],
    init_kwargs: dict[str, Any],
    nested_model_default_partial_update: bool | None = None,
)

基类: PydanticBaseSettingsSource

用于加载在设置类初始化期间提供的值的源类。

源代码位于 .venv/lib/python3.12/site-packages/pydantic_settings/sources.py
385
386
387
388
389
390
391
392
393
394
395
396
397
def __init__(
    self,
    settings_cls: type[BaseSettings],
    init_kwargs: dict[str, Any],
    nested_model_default_partial_update: bool | None = None,
):
    self.init_kwargs = init_kwargs
    super().__init__(settings_cls)
    self.nested_model_default_partial_update = (
        nested_model_default_partial_update
        if nested_model_default_partial_update is not None
        else self.config.get('nested_model_default_partial_update', False)
    )

JsonConfigSettingsSource

JsonConfigSettingsSource(
    settings_cls: type[BaseSettings],
    json_file: PathType | None = DEFAULT_PATH,
    json_file_encoding: str | None = None,
)

基类: InitSettingsSource, ConfigFileSourceMixin

一个从 JSON 文件加载变量的源类

源代码位于 .venv/lib/python3.12/site-packages/pydantic_settings/sources.py
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
def __init__(
    self,
    settings_cls: type[BaseSettings],
    json_file: PathType | None = DEFAULT_PATH,
    json_file_encoding: str | None = None,
):
    self.json_file_path = json_file if json_file != DEFAULT_PATH else settings_cls.model_config.get('json_file')
    self.json_file_encoding = (
        json_file_encoding
        if json_file_encoding is not None
        else settings_cls.model_config.get('json_file_encoding')
    )
    self.json_data = self._read_files(self.json_file_path)
    super().__init__(settings_cls, self.json_data)

NoDecode

防止解码字段值的注解。

PydanticBaseSettingsSource

PydanticBaseSettingsSource(
    settings_cls: type[BaseSettings],
)

基类: ABC

设置源的抽象基类,每个设置源类都应从中继承。

源代码位于 .venv/lib/python3.12/site-packages/pydantic_settings/sources.py
236
237
238
239
240
def __init__(self, settings_cls: type[BaseSettings]):
    self.settings_cls = settings_cls
    self.config = settings_cls.model_config
    self._current_state: dict[str, Any] = {}
    self._settings_sources_data: dict[str, dict[str, Any]] = {}

current_state property

current_state: dict[str, Any]

设置的当前状态,由先前的设置源填充。

settings_sources_data property

settings_sources_data: dict[str, dict[str, Any]]

所有先前的设置源的状态。

get_field_value abstractmethod

get_field_value(
    field: FieldInfo, field_name: str
) -> tuple[Any, str, bool]

获取值、模型创建的键以及一个标志,用于确定值是否复杂。

这是一个抽象方法,应在每个设置源类中重写。

参数

名称 类型 描述 默认值
field FieldInfo

字段。

required
field_name str

字段名称。

required

返回

类型 描述
tuple[Any, str, bool]

一个元组,包含值、键以及一个标志,用于确定值是否复杂。

源代码位于 .venv/lib/python3.12/site-packages/pydantic_settings/sources.py
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
@abstractmethod
def get_field_value(self, field: FieldInfo, field_name: str) -> tuple[Any, str, bool]:
    """
    Gets the value, the key for model creation, and a flag to determine whether value is complex.

    This is an abstract method that should be overridden in every settings source classes.

    Args:
        field: The field.
        field_name: The field name.

    Returns:
        A tuple that contains the value, key and a flag to determine whether value is complex.
    """
    pass

field_is_complex

field_is_complex(field: FieldInfo) -> bool

检查字段是否复杂,如果是,则会尝试将其解析为 JSON。

参数

名称 类型 描述 默认值
field FieldInfo

字段。

required

返回

类型 描述
bool

字段是否复杂。

源代码位于 .venv/lib/python3.12/site-packages/pydantic_settings/sources.py
286
287
288
289
290
291
292
293
294
295
296
def field_is_complex(self, field: FieldInfo) -> bool:
    """
    Checks whether a field is complex, in which case it will attempt to be parsed as JSON.

    Args:
        field: The field.

    Returns:
        Whether the field is complex.
    """
    return _annotation_is_complex(field.annotation, field.metadata)

prepare_field_value

prepare_field_value(
    field_name: str,
    field: FieldInfo,
    value: Any,
    value_is_complex: bool,
) -> Any

准备字段的值。

参数

名称 类型 描述 默认值
field_name str

字段名称。

required
field FieldInfo

字段。

required
value Any

必须准备的字段的值。

required
value_is_complex bool

一个标志,用于确定值是否复杂。

required

返回

类型 描述
Any

准备好的值。

源代码位于 .venv/lib/python3.12/site-packages/pydantic_settings/sources.py
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
def prepare_field_value(self, field_name: str, field: FieldInfo, value: Any, value_is_complex: bool) -> Any:
    """
    Prepares the value of a field.

    Args:
        field_name: The field name.
        field: The field.
        value: The value of the field that has to be prepared.
        value_is_complex: A flag to determine whether value is complex.

    Returns:
        The prepared value.
    """
    if value is not None and (self.field_is_complex(field) or value_is_complex):
        return self.decode_complex_value(field_name, field, value)
    return value

decode_complex_value

decode_complex_value(
    field_name: str, field: FieldInfo, value: Any
) -> Any

解码复杂字段的值

参数

名称 类型 描述 默认值
field_name str

字段名称。

required
field FieldInfo

字段。

required
value Any

必须准备的字段的值。

required

返回

类型 描述
Any

解码后的值,用于进一步准备

源代码位于 .venv/lib/python3.12/site-packages/pydantic_settings/sources.py
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
def decode_complex_value(self, field_name: str, field: FieldInfo, value: Any) -> Any:
    """
    Decode the value for a complex field

    Args:
        field_name: The field name.
        field: The field.
        value: The value of the field that has to be prepared.

    Returns:
        The decoded value for further preparation
    """
    if field and (
        NoDecode in field.metadata
        or (self.config.get('enable_decoding') is False and ForceDecode not in field.metadata)
    ):
        return value

    return json.loads(value)

PyprojectTomlConfigSettingsSource

PyprojectTomlConfigSettingsSource(
    settings_cls: type[BaseSettings],
    toml_file: Path | None = None,
)

基类: TomlConfigSettingsSource

一个从 pyproject.toml 文件加载变量的源类。

源代码位于 .venv/lib/python3.12/site-packages/pydantic_settings/sources.py
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
def __init__(
    self,
    settings_cls: type[BaseSettings],
    toml_file: Path | None = None,
) -> None:
    self.toml_file_path = self._pick_pyproject_toml_file(
        toml_file, settings_cls.model_config.get('pyproject_toml_depth', 0)
    )
    self.toml_table_header: tuple[str, ...] = settings_cls.model_config.get(
        'pyproject_toml_table_header', ('tool', 'pydantic-settings')
    )
    self.toml_data = self._read_files(self.toml_file_path)
    for key in self.toml_table_header:
        self.toml_data = self.toml_data.get(key, {})
    super(TomlConfigSettingsSource, self).__init__(settings_cls, self.toml_data)

SecretsSettingsSource

SecretsSettingsSource(
    settings_cls: type[BaseSettings],
    secrets_dir: PathType | None = None,
    case_sensitive: bool | None = None,
    env_prefix: str | None = None,
    env_ignore_empty: bool | None = None,
    env_parse_none_str: str | None = None,
    env_parse_enums: bool | None = None,
)

基类: PydanticBaseEnvSettingsSource

用于从密钥文件加载设置值的源类。

源代码位于 .venv/lib/python3.12/site-packages/pydantic_settings/sources.py
629
630
631
632
633
634
635
636
637
638
639
640
641
642
def __init__(
    self,
    settings_cls: type[BaseSettings],
    secrets_dir: PathType | None = None,
    case_sensitive: bool | None = None,
    env_prefix: str | None = None,
    env_ignore_empty: bool | None = None,
    env_parse_none_str: str | None = None,
    env_parse_enums: bool | None = None,
) -> None:
    super().__init__(
        settings_cls, case_sensitive, env_prefix, env_ignore_empty, env_parse_none_str, env_parse_enums
    )
    self.secrets_dir = secrets_dir if secrets_dir is not None else self.config.get('secrets_dir')

find_case_path classmethod

find_case_path(
    dir_path: Path, file_name: str, case_sensitive: bool
) -> Path | None

在路径目录中查找与文件名匹配的文件,可以选择忽略大小写。

参数

名称 类型 描述 默认值
dir_path Path

目录路径。

required
file_name str

文件名。

required
case_sensitive bool

是否区分大小写搜索文件名。

required

返回

类型 描述
Path | None

文件路径,如果目录中不存在该文件,则为 None

源代码位于 .venv/lib/python3.12/site-packages/pydantic_settings/sources.py
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
@classmethod
def find_case_path(cls, dir_path: Path, file_name: str, case_sensitive: bool) -> Path | None:
    """
    Find a file within path's directory matching filename, optionally ignoring case.

    Args:
        dir_path: Directory path.
        file_name: File name.
        case_sensitive: Whether to search for file name case sensitively.

    Returns:
        Whether file path or `None` if file does not exist in directory.
    """
    for f in dir_path.iterdir():
        if f.name == file_name:
            return f
        elif not case_sensitive and f.name.lower() == file_name.lower():
            return f
    return None

get_field_value

get_field_value(
    field: FieldInfo, field_name: str
) -> tuple[Any, str, bool]

从密钥文件获取字段的值,以及一个标志,用于确定值是否复杂。

参数

名称 类型 描述 默认值
field FieldInfo

字段。

required
field_name str

字段名称。

required

返回

类型 描述
tuple[Any, str, bool]

一个元组,包含值(如果文件不存在则为 None)、键以及一个标志,用于确定值是否复杂。

源代码位于 .venv/lib/python3.12/site-packages/pydantic_settings/sources.py
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
def get_field_value(self, field: FieldInfo, field_name: str) -> tuple[Any, str, bool]:
    """
    Gets the value for field from secret file and a flag to determine whether value is complex.

    Args:
        field: The field.
        field_name: The field name.

    Returns:
        A tuple that contains the value (`None` if the file does not exist), key, and
            a flag to determine whether value is complex.
    """

    for field_key, env_name, value_is_complex in self._extract_field_info(field, field_name):
        # paths reversed to match the last-wins behaviour of `env_file`
        for secrets_path in reversed(self.secrets_paths):
            path = self.find_case_path(secrets_path, env_name, self.case_sensitive)
            if not path:
                # path does not exist, we currently don't return a warning for this
                continue

            if path.is_file():
                return path.read_text().strip(), field_key, value_is_complex
            else:
                warnings.warn(
                    f'attempted to load secret file "{path}" but found a {path_type_label(path)} instead.',
                    stacklevel=4,
                )

    return None, field_key, value_is_complex

TomlConfigSettingsSource

TomlConfigSettingsSource(
    settings_cls: type[BaseSettings],
    toml_file: PathType | None = DEFAULT_PATH,
)

基类: InitSettingsSource, ConfigFileSourceMixin

一个从 TOML 文件加载变量的源类

源代码位于 .venv/lib/python3.12/site-packages/pydantic_settings/sources.py
2043
2044
2045
2046
2047
2048
2049
2050
def __init__(
    self,
    settings_cls: type[BaseSettings],
    toml_file: PathType | None = DEFAULT_PATH,
):
    self.toml_file_path = toml_file if toml_file != DEFAULT_PATH else settings_cls.model_config.get('toml_file')
    self.toml_data = self._read_files(self.toml_file_path)
    super().__init__(settings_cls, self.toml_data)

YamlConfigSettingsSource

YamlConfigSettingsSource(
    settings_cls: type[BaseSettings],
    yaml_file: PathType | None = DEFAULT_PATH,
    yaml_file_encoding: str | None = None,
)

基类: InitSettingsSource, ConfigFileSourceMixin

一个从 yaml 文件加载变量的源类

源代码位于 .venv/lib/python3.12/site-packages/pydantic_settings/sources.py
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
def __init__(
    self,
    settings_cls: type[BaseSettings],
    yaml_file: PathType | None = DEFAULT_PATH,
    yaml_file_encoding: str | None = None,
):
    self.yaml_file_path = yaml_file if yaml_file != DEFAULT_PATH else settings_cls.model_config.get('yaml_file')
    self.yaml_file_encoding = (
        yaml_file_encoding
        if yaml_file_encoding is not None
        else settings_cls.model_config.get('yaml_file_encoding')
    )
    self.yaml_data = self._read_files(self.yaml_file_path)
    super().__init__(settings_cls, self.yaml_data)

get_subcommand

get_subcommand(
    model: PydanticModel,
    is_required: bool = True,
    cli_exit_on_error: bool | None = None,
) -> Optional[PydanticModel]

从模型中获取子命令。

参数

名称 类型 描述 默认值
model PydanticModel

从中获取子命令的模型。

required
is_required bool

确定模型是否必须设置子命令,如果未找到则引发错误。默认为 True

True
cli_exit_on_error bool | None

确定如果未找到子命令,此函数是否退出并显示错误。如果设置了 model_config cli_exit_on_error 值,则默认为该值。否则,默认为 True

None

返回

类型 描述
Optional[PydanticModel]

找到的子命令模型,否则为 None

引发

类型 描述
SystemExit

当未找到子命令且 is_required=True 且 cli_exit_on_error=True(默认值)时。

SettingsError

当未找到子命令且 is_required=True 且 cli_exit_on_error=False 时。

源代码位于 .venv/lib/python3.12/site-packages/pydantic_settings/sources.py
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
def get_subcommand(
    model: PydanticModel, is_required: bool = True, cli_exit_on_error: bool | None = None
) -> Optional[PydanticModel]:
    """
    Get the subcommand from a model.

    Args:
        model: The model to get the subcommand from.
        is_required: Determines whether a model must have subcommand set and raises error if not
            found. Defaults to `True`.
        cli_exit_on_error: Determines whether this function exits with error if no subcommand is found.
            Defaults to model_config `cli_exit_on_error` value if set. Otherwise, defaults to `True`.

    Returns:
        The subcommand model if found, otherwise `None`.

    Raises:
        SystemExit: When no subcommand is found and is_required=`True` and cli_exit_on_error=`True`
            (the default).
        SettingsError: When no subcommand is found and is_required=`True` and
            cli_exit_on_error=`False`.
    """

    model_cls = type(model)
    if cli_exit_on_error is None and is_model_class(model_cls):
        model_default = model_cls.model_config.get('cli_exit_on_error')
        if isinstance(model_default, bool):
            cli_exit_on_error = model_default
    if cli_exit_on_error is None:
        cli_exit_on_error = True

    subcommands: list[str] = []
    for field_name, field_info in _get_model_fields(model_cls).items():
        if _CliSubCommand in field_info.metadata:
            if getattr(model, field_name) is not None:
                return getattr(model, field_name)
            subcommands.append(field_name)

    if is_required:
        error_message = (
            f'Error: CLI subcommand is required {{{", ".join(subcommands)}}}'
            if subcommands
            else 'Error: CLI subcommand is required but no subcommands were found.'
        )
        raise SystemExit(error_message) if cli_exit_on_error else SettingsError(error_message)

    return None