#!/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, )