yaml_loader.py 3.1 KB
Newer Older
Weizhi Cui's avatar
Weizhi Cui committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
#!/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

崔为之's avatar
崔为之 committed
20
from application.common import FileHelper
Weizhi Cui's avatar
Weizhi Cui committed
21 22 23 24 25
from application.lib import LocalConfig

IDENTIFIER = "yaml_loader"


崔为之's avatar
崔为之 committed
26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61
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()
        }


Weizhi Cui's avatar
Weizhi Cui committed
62 63 64 65 66 67 68
def load(
    obj: LazySettings,
    env: str = None,
    silent: bool = True,
    key: str = None,
    validate=False,
) -> Union[bool, None]:
崔为之's avatar
崔为之 committed
69 70 71 72 73 74 75 76 77 78
    """
    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.
    """
Weizhi Cui's avatar
Weizhi Cui committed
79 80
    if obj.get('Consul', False):
        return
崔为之's avatar
崔为之 committed
81

Weizhi Cui's avatar
Weizhi Cui committed
82 83 84
    config_dir = os.path.join(str(Path(__file__).parent.parent.parent), 'config')
    local_cfg = LocalConfig(config_dir)

崔为之's avatar
崔为之 committed
85 86
    filename = FileHelper.get_filename(env)
    cfg = load_config(local_cfg, filename, key)
Weizhi Cui's avatar
Weizhi Cui committed
87 88

    try:
崔为之's avatar
崔为之 committed
89 90
        result = parse_config(cfg, env, obj)
    except KeyError as e:
Weizhi Cui's avatar
Weizhi Cui committed
91 92 93
        if silent:
            return False
        raise e
崔为之's avatar
崔为之 committed
94 95 96 97 98 99 100

    if result:
        obj.update(
            result,
            loader_identifier=IDENTIFIER,
            validate=validate,
        )