main.py 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539
  1. from __future__ import annotations as _annotations
  2. from argparse import Namespace
  3. from types import SimpleNamespace
  4. from typing import Any, ClassVar, TypeVar
  5. from pydantic import AliasGenerator, ConfigDict
  6. from pydantic._internal._config import config_keys
  7. from pydantic._internal._signature import _field_name_for_signature
  8. from pydantic._internal._utils import deep_update, is_model_class
  9. from pydantic.dataclasses import is_pydantic_dataclass
  10. from pydantic.main import BaseModel
  11. from .sources import (
  12. ENV_FILE_SENTINEL,
  13. CliSettingsSource,
  14. DefaultSettingsSource,
  15. DotEnvSettingsSource,
  16. DotenvType,
  17. EnvSettingsSource,
  18. InitSettingsSource,
  19. PathType,
  20. PydanticBaseSettingsSource,
  21. PydanticModel,
  22. SecretsSettingsSource,
  23. SettingsError,
  24. get_subcommand,
  25. )
  26. T = TypeVar('T')
  27. class SettingsConfigDict(ConfigDict, total=False):
  28. case_sensitive: bool
  29. nested_model_default_partial_update: bool | None
  30. env_prefix: str
  31. env_file: DotenvType | None
  32. env_file_encoding: str | None
  33. env_ignore_empty: bool
  34. env_nested_delimiter: str | None
  35. env_parse_none_str: str | None
  36. env_parse_enums: bool | None
  37. cli_prog_name: str | None
  38. cli_parse_args: bool | list[str] | tuple[str, ...] | None
  39. cli_parse_none_str: str | None
  40. cli_hide_none_type: bool
  41. cli_avoid_json: bool
  42. cli_enforce_required: bool
  43. cli_use_class_docs_for_groups: bool
  44. cli_exit_on_error: bool
  45. cli_prefix: str
  46. cli_flag_prefix_char: str
  47. cli_implicit_flags: bool | None
  48. cli_ignore_unknown_args: bool | None
  49. secrets_dir: PathType | None
  50. json_file: PathType | None
  51. json_file_encoding: str | None
  52. yaml_file: PathType | None
  53. yaml_file_encoding: str | None
  54. pyproject_toml_depth: int
  55. """
  56. Number of levels **up** from the current working directory to attempt to find a pyproject.toml
  57. file.
  58. This is only used when a pyproject.toml file is not found in the current working directory.
  59. """
  60. pyproject_toml_table_header: tuple[str, ...]
  61. """
  62. Header of the TOML table within a pyproject.toml file to use when filling variables.
  63. This is supplied as a `tuple[str, ...]` instead of a `str` to accommodate for headers
  64. containing a `.`.
  65. For example, `toml_table_header = ("tool", "my.tool", "foo")` can be used to fill variable
  66. values from a table with header `[tool."my.tool".foo]`.
  67. To use the root table, exclude this config setting or provide an empty tuple.
  68. """
  69. toml_file: PathType | None
  70. # Extend `config_keys` by pydantic settings config keys to
  71. # support setting config through class kwargs.
  72. # Pydantic uses `config_keys` in `pydantic._internal._config.ConfigWrapper.for_model`
  73. # to extract config keys from model kwargs, So, by adding pydantic settings keys to
  74. # `config_keys`, they will be considered as valid config keys and will be collected
  75. # by Pydantic.
  76. config_keys |= set(SettingsConfigDict.__annotations__.keys())
  77. class BaseSettings(BaseModel):
  78. """
  79. Base class for settings, allowing values to be overridden by environment variables.
  80. This is useful in production for secrets you do not wish to save in code, it plays nicely with docker(-compose),
  81. Heroku and any 12 factor app design.
  82. All the below attributes can be set via `model_config`.
  83. Args:
  84. _case_sensitive: Whether environment and CLI variable names should be read with case-sensitivity.
  85. Defaults to `None`.
  86. _nested_model_default_partial_update: Whether to allow partial updates on nested model default object fields.
  87. Defaults to `False`.
  88. _env_prefix: Prefix for all environment variables. Defaults to `None`.
  89. _env_file: The env file(s) to load settings values from. Defaults to `Path('')`, which
  90. means that the value from `model_config['env_file']` should be used. You can also pass
  91. `None` to indicate that environment variables should not be loaded from an env file.
  92. _env_file_encoding: The env file encoding, e.g. `'latin-1'`. Defaults to `None`.
  93. _env_ignore_empty: Ignore environment variables where the value is an empty string. Default to `False`.
  94. _env_nested_delimiter: The nested env values delimiter. Defaults to `None`.
  95. _env_parse_none_str: The env string value that should be parsed (e.g. "null", "void", "None", etc.)
  96. into `None` type(None). Defaults to `None` type(None), which means no parsing should occur.
  97. _env_parse_enums: Parse enum field names to values. Defaults to `None.`, which means no parsing should occur.
  98. _cli_prog_name: The CLI program name to display in help text. Defaults to `None` if _cli_parse_args is `None`.
  99. Otherwse, defaults to sys.argv[0].
  100. _cli_parse_args: The list of CLI arguments to parse. Defaults to None.
  101. If set to `True`, defaults to sys.argv[1:].
  102. _cli_settings_source: Override the default CLI settings source with a user defined instance. Defaults to None.
  103. _cli_parse_none_str: The CLI string value that should be parsed (e.g. "null", "void", "None", etc.) into
  104. `None` type(None). Defaults to _env_parse_none_str value if set. Otherwise, defaults to "null" if
  105. _cli_avoid_json is `False`, and "None" if _cli_avoid_json is `True`.
  106. _cli_hide_none_type: Hide `None` values in CLI help text. Defaults to `False`.
  107. _cli_avoid_json: Avoid complex JSON objects in CLI help text. Defaults to `False`.
  108. _cli_enforce_required: Enforce required fields at the CLI. Defaults to `False`.
  109. _cli_use_class_docs_for_groups: Use class docstrings in CLI group help text instead of field descriptions.
  110. Defaults to `False`.
  111. _cli_exit_on_error: Determines whether or not the internal parser exits with error info when an error occurs.
  112. Defaults to `True`.
  113. _cli_prefix: The root parser command line arguments prefix. Defaults to "".
  114. _cli_flag_prefix_char: The flag prefix character to use for CLI optional arguments. Defaults to '-'.
  115. _cli_implicit_flags: Whether `bool` fields should be implicitly converted into CLI boolean flags.
  116. (e.g. --flag, --no-flag). Defaults to `False`.
  117. _cli_ignore_unknown_args: Whether to ignore unknown CLI args and parse only known ones. Defaults to `False`.
  118. _secrets_dir: The secret files directory or a sequence of directories. Defaults to `None`.
  119. """
  120. def __init__(
  121. __pydantic_self__,
  122. _case_sensitive: bool | None = None,
  123. _nested_model_default_partial_update: bool | None = None,
  124. _env_prefix: str | None = None,
  125. _env_file: DotenvType | None = ENV_FILE_SENTINEL,
  126. _env_file_encoding: str | None = None,
  127. _env_ignore_empty: bool | None = None,
  128. _env_nested_delimiter: str | None = None,
  129. _env_parse_none_str: str | None = None,
  130. _env_parse_enums: bool | None = None,
  131. _cli_prog_name: str | None = None,
  132. _cli_parse_args: bool | list[str] | tuple[str, ...] | None = None,
  133. _cli_settings_source: CliSettingsSource[Any] | None = None,
  134. _cli_parse_none_str: str | None = None,
  135. _cli_hide_none_type: bool | None = None,
  136. _cli_avoid_json: bool | None = None,
  137. _cli_enforce_required: bool | None = None,
  138. _cli_use_class_docs_for_groups: bool | None = None,
  139. _cli_exit_on_error: bool | None = None,
  140. _cli_prefix: str | None = None,
  141. _cli_flag_prefix_char: str | None = None,
  142. _cli_implicit_flags: bool | None = None,
  143. _cli_ignore_unknown_args: bool | None = None,
  144. _secrets_dir: PathType | None = None,
  145. **values: Any,
  146. ) -> None:
  147. # Uses something other than `self` the first arg to allow "self" as a settable attribute
  148. super().__init__(
  149. **__pydantic_self__._settings_build_values(
  150. values,
  151. _case_sensitive=_case_sensitive,
  152. _nested_model_default_partial_update=_nested_model_default_partial_update,
  153. _env_prefix=_env_prefix,
  154. _env_file=_env_file,
  155. _env_file_encoding=_env_file_encoding,
  156. _env_ignore_empty=_env_ignore_empty,
  157. _env_nested_delimiter=_env_nested_delimiter,
  158. _env_parse_none_str=_env_parse_none_str,
  159. _env_parse_enums=_env_parse_enums,
  160. _cli_prog_name=_cli_prog_name,
  161. _cli_parse_args=_cli_parse_args,
  162. _cli_settings_source=_cli_settings_source,
  163. _cli_parse_none_str=_cli_parse_none_str,
  164. _cli_hide_none_type=_cli_hide_none_type,
  165. _cli_avoid_json=_cli_avoid_json,
  166. _cli_enforce_required=_cli_enforce_required,
  167. _cli_use_class_docs_for_groups=_cli_use_class_docs_for_groups,
  168. _cli_exit_on_error=_cli_exit_on_error,
  169. _cli_prefix=_cli_prefix,
  170. _cli_flag_prefix_char=_cli_flag_prefix_char,
  171. _cli_implicit_flags=_cli_implicit_flags,
  172. _cli_ignore_unknown_args=_cli_ignore_unknown_args,
  173. _secrets_dir=_secrets_dir,
  174. )
  175. )
  176. @classmethod
  177. def settings_customise_sources(
  178. cls,
  179. settings_cls: type[BaseSettings],
  180. init_settings: PydanticBaseSettingsSource,
  181. env_settings: PydanticBaseSettingsSource,
  182. dotenv_settings: PydanticBaseSettingsSource,
  183. file_secret_settings: PydanticBaseSettingsSource,
  184. ) -> tuple[PydanticBaseSettingsSource, ...]:
  185. """
  186. Define the sources and their order for loading the settings values.
  187. Args:
  188. settings_cls: The Settings class.
  189. init_settings: The `InitSettingsSource` instance.
  190. env_settings: The `EnvSettingsSource` instance.
  191. dotenv_settings: The `DotEnvSettingsSource` instance.
  192. file_secret_settings: The `SecretsSettingsSource` instance.
  193. Returns:
  194. A tuple containing the sources and their order for loading the settings values.
  195. """
  196. return init_settings, env_settings, dotenv_settings, file_secret_settings
  197. def _settings_build_values(
  198. self,
  199. init_kwargs: dict[str, Any],
  200. _case_sensitive: bool | None = None,
  201. _nested_model_default_partial_update: bool | None = None,
  202. _env_prefix: str | None = None,
  203. _env_file: DotenvType | None = None,
  204. _env_file_encoding: str | None = None,
  205. _env_ignore_empty: bool | None = None,
  206. _env_nested_delimiter: str | None = None,
  207. _env_parse_none_str: str | None = None,
  208. _env_parse_enums: bool | None = None,
  209. _cli_prog_name: str | None = None,
  210. _cli_parse_args: bool | list[str] | tuple[str, ...] | None = None,
  211. _cli_settings_source: CliSettingsSource[Any] | None = None,
  212. _cli_parse_none_str: str | None = None,
  213. _cli_hide_none_type: bool | None = None,
  214. _cli_avoid_json: bool | None = None,
  215. _cli_enforce_required: bool | None = None,
  216. _cli_use_class_docs_for_groups: bool | None = None,
  217. _cli_exit_on_error: bool | None = None,
  218. _cli_prefix: str | None = None,
  219. _cli_flag_prefix_char: str | None = None,
  220. _cli_implicit_flags: bool | None = None,
  221. _cli_ignore_unknown_args: bool | None = None,
  222. _secrets_dir: PathType | None = None,
  223. ) -> dict[str, Any]:
  224. # Determine settings config values
  225. case_sensitive = _case_sensitive if _case_sensitive is not None else self.model_config.get('case_sensitive')
  226. env_prefix = _env_prefix if _env_prefix is not None else self.model_config.get('env_prefix')
  227. nested_model_default_partial_update = (
  228. _nested_model_default_partial_update
  229. if _nested_model_default_partial_update is not None
  230. else self.model_config.get('nested_model_default_partial_update')
  231. )
  232. env_file = _env_file if _env_file != ENV_FILE_SENTINEL else self.model_config.get('env_file')
  233. env_file_encoding = (
  234. _env_file_encoding if _env_file_encoding is not None else self.model_config.get('env_file_encoding')
  235. )
  236. env_ignore_empty = (
  237. _env_ignore_empty if _env_ignore_empty is not None else self.model_config.get('env_ignore_empty')
  238. )
  239. env_nested_delimiter = (
  240. _env_nested_delimiter
  241. if _env_nested_delimiter is not None
  242. else self.model_config.get('env_nested_delimiter')
  243. )
  244. env_parse_none_str = (
  245. _env_parse_none_str if _env_parse_none_str is not None else self.model_config.get('env_parse_none_str')
  246. )
  247. env_parse_enums = _env_parse_enums if _env_parse_enums is not None else self.model_config.get('env_parse_enums')
  248. cli_prog_name = _cli_prog_name if _cli_prog_name is not None else self.model_config.get('cli_prog_name')
  249. cli_parse_args = _cli_parse_args if _cli_parse_args is not None else self.model_config.get('cli_parse_args')
  250. cli_settings_source = (
  251. _cli_settings_source if _cli_settings_source is not None else self.model_config.get('cli_settings_source')
  252. )
  253. cli_parse_none_str = (
  254. _cli_parse_none_str if _cli_parse_none_str is not None else self.model_config.get('cli_parse_none_str')
  255. )
  256. cli_parse_none_str = cli_parse_none_str if not env_parse_none_str else env_parse_none_str
  257. cli_hide_none_type = (
  258. _cli_hide_none_type if _cli_hide_none_type is not None else self.model_config.get('cli_hide_none_type')
  259. )
  260. cli_avoid_json = _cli_avoid_json if _cli_avoid_json is not None else self.model_config.get('cli_avoid_json')
  261. cli_enforce_required = (
  262. _cli_enforce_required
  263. if _cli_enforce_required is not None
  264. else self.model_config.get('cli_enforce_required')
  265. )
  266. cli_use_class_docs_for_groups = (
  267. _cli_use_class_docs_for_groups
  268. if _cli_use_class_docs_for_groups is not None
  269. else self.model_config.get('cli_use_class_docs_for_groups')
  270. )
  271. cli_exit_on_error = (
  272. _cli_exit_on_error if _cli_exit_on_error is not None else self.model_config.get('cli_exit_on_error')
  273. )
  274. cli_prefix = _cli_prefix if _cli_prefix is not None else self.model_config.get('cli_prefix')
  275. cli_flag_prefix_char = (
  276. _cli_flag_prefix_char
  277. if _cli_flag_prefix_char is not None
  278. else self.model_config.get('cli_flag_prefix_char')
  279. )
  280. cli_implicit_flags = (
  281. _cli_implicit_flags if _cli_implicit_flags is not None else self.model_config.get('cli_implicit_flags')
  282. )
  283. cli_ignore_unknown_args = (
  284. _cli_ignore_unknown_args
  285. if _cli_ignore_unknown_args is not None
  286. else self.model_config.get('cli_ignore_unknown_args')
  287. )
  288. secrets_dir = _secrets_dir if _secrets_dir is not None else self.model_config.get('secrets_dir')
  289. # Configure built-in sources
  290. default_settings = DefaultSettingsSource(
  291. self.__class__, nested_model_default_partial_update=nested_model_default_partial_update
  292. )
  293. init_settings = InitSettingsSource(
  294. self.__class__,
  295. init_kwargs=init_kwargs,
  296. nested_model_default_partial_update=nested_model_default_partial_update,
  297. )
  298. env_settings = EnvSettingsSource(
  299. self.__class__,
  300. case_sensitive=case_sensitive,
  301. env_prefix=env_prefix,
  302. env_nested_delimiter=env_nested_delimiter,
  303. env_ignore_empty=env_ignore_empty,
  304. env_parse_none_str=env_parse_none_str,
  305. env_parse_enums=env_parse_enums,
  306. )
  307. dotenv_settings = DotEnvSettingsSource(
  308. self.__class__,
  309. env_file=env_file,
  310. env_file_encoding=env_file_encoding,
  311. case_sensitive=case_sensitive,
  312. env_prefix=env_prefix,
  313. env_nested_delimiter=env_nested_delimiter,
  314. env_ignore_empty=env_ignore_empty,
  315. env_parse_none_str=env_parse_none_str,
  316. env_parse_enums=env_parse_enums,
  317. )
  318. file_secret_settings = SecretsSettingsSource(
  319. self.__class__, secrets_dir=secrets_dir, case_sensitive=case_sensitive, env_prefix=env_prefix
  320. )
  321. # Provide a hook to set built-in sources priority and add / remove sources
  322. sources = self.settings_customise_sources(
  323. self.__class__,
  324. init_settings=init_settings,
  325. env_settings=env_settings,
  326. dotenv_settings=dotenv_settings,
  327. file_secret_settings=file_secret_settings,
  328. ) + (default_settings,)
  329. if not any([source for source in sources if isinstance(source, CliSettingsSource)]):
  330. if isinstance(cli_settings_source, CliSettingsSource):
  331. sources = (cli_settings_source,) + sources
  332. elif cli_parse_args is not None:
  333. cli_settings = CliSettingsSource[Any](
  334. self.__class__,
  335. cli_prog_name=cli_prog_name,
  336. cli_parse_args=cli_parse_args,
  337. cli_parse_none_str=cli_parse_none_str,
  338. cli_hide_none_type=cli_hide_none_type,
  339. cli_avoid_json=cli_avoid_json,
  340. cli_enforce_required=cli_enforce_required,
  341. cli_use_class_docs_for_groups=cli_use_class_docs_for_groups,
  342. cli_exit_on_error=cli_exit_on_error,
  343. cli_prefix=cli_prefix,
  344. cli_flag_prefix_char=cli_flag_prefix_char,
  345. cli_implicit_flags=cli_implicit_flags,
  346. cli_ignore_unknown_args=cli_ignore_unknown_args,
  347. case_sensitive=case_sensitive,
  348. )
  349. sources = (cli_settings,) + sources
  350. if sources:
  351. state: dict[str, Any] = {}
  352. states: dict[str, dict[str, Any]] = {}
  353. for source in sources:
  354. if isinstance(source, PydanticBaseSettingsSource):
  355. source._set_current_state(state)
  356. source._set_settings_sources_data(states)
  357. source_name = source.__name__ if hasattr(source, '__name__') else type(source).__name__
  358. source_state = source()
  359. states[source_name] = source_state
  360. state = deep_update(source_state, state)
  361. return state
  362. else:
  363. # no one should mean to do this, but I think returning an empty dict is marginally preferable
  364. # to an informative error and much better than a confusing error
  365. return {}
  366. model_config: ClassVar[SettingsConfigDict] = SettingsConfigDict(
  367. extra='forbid',
  368. arbitrary_types_allowed=True,
  369. validate_default=True,
  370. case_sensitive=False,
  371. env_prefix='',
  372. nested_model_default_partial_update=False,
  373. env_file=None,
  374. env_file_encoding=None,
  375. env_ignore_empty=False,
  376. env_nested_delimiter=None,
  377. env_parse_none_str=None,
  378. env_parse_enums=None,
  379. cli_prog_name=None,
  380. cli_parse_args=None,
  381. cli_parse_none_str=None,
  382. cli_hide_none_type=False,
  383. cli_avoid_json=False,
  384. cli_enforce_required=False,
  385. cli_use_class_docs_for_groups=False,
  386. cli_exit_on_error=True,
  387. cli_prefix='',
  388. cli_flag_prefix_char='-',
  389. cli_implicit_flags=False,
  390. cli_ignore_unknown_args=False,
  391. json_file=None,
  392. json_file_encoding=None,
  393. yaml_file=None,
  394. yaml_file_encoding=None,
  395. toml_file=None,
  396. secrets_dir=None,
  397. protected_namespaces=('model_', 'settings_'),
  398. )
  399. class CliApp:
  400. """
  401. A utility class for running Pydantic `BaseSettings`, `BaseModel`, or `pydantic.dataclasses.dataclass` as
  402. CLI applications.
  403. """
  404. @staticmethod
  405. def _run_cli_cmd(model: Any, cli_cmd_method_name: str, is_required: bool) -> Any:
  406. if hasattr(type(model), cli_cmd_method_name):
  407. getattr(type(model), cli_cmd_method_name)(model)
  408. elif is_required:
  409. raise SettingsError(f'Error: {type(model).__name__} class is missing {cli_cmd_method_name} entrypoint')
  410. return model
  411. @staticmethod
  412. def run(
  413. model_cls: type[T],
  414. cli_args: list[str] | Namespace | SimpleNamespace | dict[str, Any] | None = None,
  415. cli_settings_source: CliSettingsSource[Any] | None = None,
  416. cli_exit_on_error: bool | None = None,
  417. cli_cmd_method_name: str = 'cli_cmd',
  418. **model_init_data: Any,
  419. ) -> T:
  420. """
  421. Runs a Pydantic `BaseSettings`, `BaseModel`, or `pydantic.dataclasses.dataclass` as a CLI application.
  422. Running a model as a CLI application requires the `cli_cmd` method to be defined in the model class.
  423. Args:
  424. model_cls: The model class to run as a CLI application.
  425. cli_args: The list of CLI arguments to parse. If `cli_settings_source` is specified, this may
  426. also be a namespace or dictionary of pre-parsed CLI arguments. Defaults to `sys.argv[1:]`.
  427. cli_settings_source: Override the default CLI settings source with a user defined instance.
  428. Defaults to `None`.
  429. cli_exit_on_error: Determines whether this function exits on error. If model is subclass of
  430. `BaseSettings`, defaults to BaseSettings `cli_exit_on_error` value. Otherwise, defaults to
  431. `True`.
  432. cli_cmd_method_name: The CLI command method name to run. Defaults to "cli_cmd".
  433. model_init_data: The model init data.
  434. Returns:
  435. The ran instance of model.
  436. Raises:
  437. SettingsError: If model_cls is not subclass of `BaseModel` or `pydantic.dataclasses.dataclass`.
  438. SettingsError: If model_cls does not have a `cli_cmd` entrypoint defined.
  439. """
  440. if not (is_pydantic_dataclass(model_cls) or is_model_class(model_cls)):
  441. raise SettingsError(
  442. f'Error: {model_cls.__name__} is not subclass of BaseModel or pydantic.dataclasses.dataclass'
  443. )
  444. cli_settings = None
  445. cli_parse_args = True if cli_args is None else cli_args
  446. if cli_settings_source is not None:
  447. if isinstance(cli_parse_args, (Namespace, SimpleNamespace, dict)):
  448. cli_settings = cli_settings_source(parsed_args=cli_parse_args)
  449. else:
  450. cli_settings = cli_settings_source(args=cli_parse_args)
  451. elif isinstance(cli_parse_args, (Namespace, SimpleNamespace, dict)):
  452. raise SettingsError('Error: `cli_args` must be list[str] or None when `cli_settings_source` is not used')
  453. model_init_data['_cli_parse_args'] = cli_parse_args
  454. model_init_data['_cli_exit_on_error'] = cli_exit_on_error
  455. model_init_data['_cli_settings_source'] = cli_settings
  456. if not issubclass(model_cls, BaseSettings):
  457. class CliAppBaseSettings(BaseSettings, model_cls): # type: ignore
  458. model_config = SettingsConfigDict(
  459. alias_generator=AliasGenerator(lambda s: s.replace('_', '-')),
  460. nested_model_default_partial_update=True,
  461. case_sensitive=True,
  462. cli_hide_none_type=True,
  463. cli_avoid_json=True,
  464. cli_enforce_required=True,
  465. cli_implicit_flags=True,
  466. )
  467. model = CliAppBaseSettings(**model_init_data)
  468. model_init_data = {}
  469. for field_name, field_info in model.model_fields.items():
  470. model_init_data[_field_name_for_signature(field_name, field_info)] = getattr(model, field_name)
  471. return CliApp._run_cli_cmd(model_cls(**model_init_data), cli_cmd_method_name, is_required=False)
  472. @staticmethod
  473. def run_subcommand(
  474. model: PydanticModel, cli_exit_on_error: bool | None = None, cli_cmd_method_name: str = 'cli_cmd'
  475. ) -> PydanticModel:
  476. """
  477. Runs the model subcommand. Running a model subcommand requires the `cli_cmd` method to be defined in
  478. the nested model subcommand class.
  479. Args:
  480. model: The model to run the subcommand from.
  481. cli_exit_on_error: Determines whether this function exits with error if no subcommand is found.
  482. Defaults to model_config `cli_exit_on_error` value if set. Otherwise, defaults to `True`.
  483. cli_cmd_method_name: The CLI command method name to run. Defaults to "cli_cmd".
  484. Returns:
  485. The ran subcommand model.
  486. Raises:
  487. SystemExit: When no subcommand is found and cli_exit_on_error=`True` (the default).
  488. SettingsError: When no subcommand is found and cli_exit_on_error=`False`.
  489. """
  490. subcommand = get_subcommand(model, is_required=True, cli_exit_on_error=cli_exit_on_error)
  491. return CliApp._run_cli_cmd(subcommand, cli_cmd_method_name, is_required=True)