consul_loader.py 2.36 KB
Newer Older
Weizhi Cui's avatar
Weizhi Cui committed
1 2 3 4 5 6 7 8 9 10 11 12
#!/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 12:16
# @File        : consul_loader.py
# @Description :
"""

崔为之's avatar
崔为之 committed
13
from typing import Union
Weizhi Cui's avatar
Weizhi Cui committed
14 15 16 17 18

import requests
from dynaconf.base import LazySettings
from dynaconf.utils.parse_conf import parse_conf_data

崔为之's avatar
崔为之 committed
19
from application.libs import ConsulConfig
崔为之's avatar
崔为之 committed
20
from application.libs.helper import EnvVarHelper
Weizhi Cui's avatar
Weizhi Cui committed
21 22 23 24

IDENTIFIER = "consul_loader"


崔为之's avatar
崔为之 committed
25
def parse_config(data: dict, key: str, obj: LazySettings) -> dict:
崔为之's avatar
崔为之 committed
26 27 28 29 30 31 32 33
    """
    Parses the configuration data.

    :param data: The configuration data.
    :param key: The key to be parsed in the configuration.
    :param obj: The LazySettings object.
    :return: A dictionary with parsed configuration data.
    """
崔为之's avatar
崔为之 committed
34 35 36 37 38 39 40
    if key is not None:
        data = data[key]

    return {
        key: parse_conf_data(value, tomlfy=True, box_settings=obj)
        for key, value in data.items()
    }
Weizhi Cui's avatar
Weizhi Cui committed
41 42 43 44 45 46 47 48 49


def load(
    obj: LazySettings,
    env: str = None,
    silent: bool = True,
    key: str = None,
    validate=False,
) -> Union[bool, None]:
崔为之's avatar
崔为之 committed
50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68
    """
    Loads the configuration data.

    :param obj: The LazySettings object.
    :param env: The environment.
    :param silent: If True, suppress exceptions.
    :param key: The key to be loaded in the configuration.
    :param validate: If True, validate the configuration.
    :return: Boolean indicating success, or None in case of failure.
    """
    # 实例化对象
    env_helper = EnvVarHelper()
    # 从环境变量获取 consul 参数
    env_vars = env_helper.consul_vars
    # 获取 consul key
    consul_key = env_vars.pop('key', None)

    # If the key is None or empty, return None
    if not consul_key:
Weizhi Cui's avatar
Weizhi Cui committed
69 70
        return

崔为之's avatar
崔为之 committed
71 72
    client = ConsulConfig(**env_vars)

Weizhi Cui's avatar
Weizhi Cui committed
73 74 75 76 77
    try:
        data = client.get(key=consul_key)
    except requests.exceptions.ConnectionError:
        return
    except Exception as e:
崔为之's avatar
崔为之 committed
78 79
        # Include original exception in the traceback
        raise RuntimeError(f'Unknown error: {e}') from e
Weizhi Cui's avatar
Weizhi Cui committed
80 81 82 83 84

    if env is None:
        return

    try:
崔为之's avatar
崔为之 committed
85
        result = parse_config(data, key, obj)
Weizhi Cui's avatar
Weizhi Cui committed
86 87 88 89
    except Exception as e:
        if silent:
            return False
        raise e
崔为之's avatar
崔为之 committed
90 91 92 93 94 95 96

    result['Consul'] = True
    obj.update(
        result,
        loader_identifier=IDENTIFIER,
        validate=validate,
    )