parse bool, int, and str key=value pairs from env
(key: str,
default: ConfigDefaultValue=None,
type: Optional[Type]=None,
aliases: Optional[Tuple[str, ...]]=None,
config: Optional[ConfigDict]=None,
env_vars: Optional[os._Environ]=None,
config_file_vars: Optional[Dict[str, str]]=None)
| 580 | |
| 581 | |
| 582 | def load_config_val(key: str, |
| 583 | default: ConfigDefaultValue=None, |
| 584 | type: Optional[Type]=None, |
| 585 | aliases: Optional[Tuple[str, ...]]=None, |
| 586 | config: Optional[ConfigDict]=None, |
| 587 | env_vars: Optional[os._Environ]=None, |
| 588 | config_file_vars: Optional[Dict[str, str]]=None) -> ConfigValue: |
| 589 | """parse bool, int, and str key=value pairs from env""" |
| 590 | |
| 591 | assert isinstance(config, dict) |
| 592 | |
| 593 | is_read_only = type is None |
| 594 | if is_read_only: |
| 595 | if callable(default): |
| 596 | return default(config) |
| 597 | return default |
| 598 | |
| 599 | # get value from environment variables or config files |
| 600 | config_keys_to_check = (key, *(aliases or ())) |
| 601 | val = None |
| 602 | for key in config_keys_to_check: |
| 603 | if env_vars: |
| 604 | val = env_vars.get(key) |
| 605 | if val: |
| 606 | break |
| 607 | |
| 608 | if config_file_vars: |
| 609 | val = config_file_vars.get(key) |
| 610 | if val: |
| 611 | break |
| 612 | |
| 613 | is_unset = val is None |
| 614 | if is_unset: |
| 615 | if callable(default): |
| 616 | return default(config) |
| 617 | return default |
| 618 | |
| 619 | # calculate value based on expected type |
| 620 | BOOL_TRUEIES = ('true', 'yes', '1') |
| 621 | BOOL_FALSEIES = ('false', 'no', '0') |
| 622 | |
| 623 | if type is bool: |
| 624 | if val.lower() in BOOL_TRUEIES: |
| 625 | return True |
| 626 | elif val.lower() in BOOL_FALSEIES: |
| 627 | return False |
| 628 | else: |
| 629 | raise ValueError(f'Invalid configuration option {key}={val} (expected a boolean: True/False)') |
| 630 | |
| 631 | elif type is str: |
| 632 | if val.lower() in (*BOOL_TRUEIES, *BOOL_FALSEIES): |
| 633 | raise ValueError(f'Invalid configuration option {key}={val} (expected a string, but value looks like a boolean)') |
| 634 | return val.strip() |
| 635 | |
| 636 | elif type is int: |
| 637 | if not val.strip().isdigit(): |
| 638 | raise ValueError(f'Invalid configuration option {key}={val} (expected an integer)') |
| 639 | return int(val.strip()) |