選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。
 
 
 
 

622 行
28 KiB

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