#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ # @Version : Python 3.11.4 # @Software : Sublime Text 4 # @Author : StudentCWZ # @Email : StudentCWZ@outlook.com # @Date : 2023/10/28 13:01 # @File : yaml_loader.py # @Description : """ import os from pathlib import Path from typing import Union from dynaconf.base import LazySettings from dynaconf.utils.parse_conf import parse_conf_data from application.libs import LocalConfig from application.libs.helper import FileHelper IDENTIFIER = "yaml_loader" def load_config(local_cfg: LocalConfig, filename: str, key: str) -> dict: """ Load the configuration from a file. :param local_cfg: a LocalConfig object for loading the config. :param filename: a string representing the name of the config file. :param key: a string representing the key to extract from the config. If it's None, return the whole config. :return: a dict representing the loaded config. """ if key is None: return local_cfg.load(filename) else: return local_cfg.load(filename)[key] def parse_config(cfg: dict, env: str, obj: LazySettings) -> dict: """ Parse the configuration based on the environment. :param cfg: a dict representing the loaded config. :param env: a string representing the environment. It should be 'PRODUCTION' or None. :param obj: a LazySettings object that the config will be applied to. :return: a dict representing the parsed config. """ if cfg.get(env) is None: return { key: parse_conf_data(value, tomlfy=True, box_settings=obj) for key, value in cfg.items() } else: return { key: parse_conf_data(value, tomlfy=True, box_settings=obj) for key, value in cfg[env].items() } def load( obj: LazySettings, env: str = None, silent: bool = True, key: str = None, validate=False, ) -> Union[bool, None]: """ Load and apply the configuration to a LazySettings object. :param obj: a LazySettings object that the config will be applied to. :param env: a string representing the environment. It should be 'PRODUCTION' or None. :param silent: a bool indicating whether to suppress the KeyError when the key is not in the config. :param key: a string representing the key to extract from the config. If it's None, apply the whole config. :param validate: a bool indicating whether to validate the config after loading. :return: None if the config is successfully applied, False if the key is not in the config and silent is True. """ if obj.get('Consul', False): return config_dir = os.path.join(str(Path(__file__).parent.parent.parent), 'config') local_cfg = LocalConfig(config_dir) filename = FileHelper.get_filename(env) cfg = load_config(local_cfg, filename, key) try: result = parse_config(cfg, env, obj) except KeyError as e: if silent: return False raise e if result: obj.update( result, loader_identifier=IDENTIFIER, validate=validate, )