yaml_loader.py 1.98 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 20 21 22 23 24 25 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 62 63 64 65 66 67 68 69 70 71 72 73 74
#!/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.lib import LocalConfig

IDENTIFIER = "yaml_loader"


def load(
    obj: LazySettings,
    env: str = None,
    silent: bool = True,
    key: str = None,
    validate=False,
) -> Union[bool, None]:
    # 判断是否已经加载 consul 配置,如果加载,则不再加载本地配置
    if obj.get('Consul', False):
        return
    # 获取本地配置文件目录
    config_dir = os.path.join(str(Path(__file__).parent.parent.parent), 'config')
    # 实例化 LocalConfig 对象
    local_cfg = LocalConfig(config_dir)

    # 判断当前是否为生产环境,基于不同环境读取本地不同配置文件
    if env == 'PRODUCTION':
        filename = f'{env.lower()}_config.yaml'
    else:
        filename = 'config.yaml'

    # 基于 key 获取所需配置
    if key is None:
        cfg = local_cfg.load(filename)
    else:
        cfg = local_cfg.load(filename)[key]

    try:
        # 将 cfg 配置写入 dynaconf 内置配置中
        if cfg.get(env) is None:
            result = {
                key: parse_conf_data(value, tomlfy=True, box_settings=obj)
                for key, value in cfg.items()
            }
        else:
            result = {
                key: parse_conf_data(value, tomlfy=True, box_settings=obj)
                for key, value in cfg[env].items()
            }
    except Exception as e:
        if silent:
            return False
        raise e
    else:
        if result:
            obj.update(
                result,
                loader_identifier=IDENTIFIER,
                validate=validate,
            )