consul.py 1.54 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
#!/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 15:06
# @File        : consul.py
# @Description :
"""

from typing import Any

import consul
import yaml


class ConsulConfig:
    def __init__(self, host='localhost', port=8500, token=None, dc='dc1'):
崔为之's avatar
崔为之 committed
21 22 23 24 25 26 27 28
        """
        Initialize a ConsulConfig instance.

        :param host: The host of the Consul server. Default is 'localhost'.
        :param port: The port of the Consul server. Default is 8500.
        :param token: The Consul token. Default is None.
        :param dc: The datacenter to use. Default is 'dc1'.
        """
Weizhi Cui's avatar
Weizhi Cui committed
29 30
        self.token = token
        self.dc = dc
崔为之's avatar
崔为之 committed
31
        # Create a Consul client instance
Weizhi Cui's avatar
Weizhi Cui committed
32 33 34
        self.client = consul.Consul(host=host, port=port, token=token, dc=dc)

    def get(self, key: str) -> Any:
崔为之's avatar
崔为之 committed
35 36 37 38 39 40 41 42
        """
        Retrieve the value of a key from the Consul KV store.

        :param key: The key to retrieve.
        :return: The value of the key.
        :raises KeyError: If the key is not found in Consul.
        """
        # Retrieve the key-value pair from Consul
Weizhi Cui's avatar
Weizhi Cui committed
43
        _, data = self.client.kv.get(key=key, token=self.token, dc=self.dc)
崔为之's avatar
崔为之 committed
44
        # If the key-value pair is not found, raise an exception
Weizhi Cui's avatar
Weizhi Cui committed
45 46
        if data is None:
            raise KeyError(f'Key {key} not found in Consul.')
崔为之's avatar
崔为之 committed
47
        # Load the value from the key-value pair as YAML
Weizhi Cui's avatar
Weizhi Cui committed
48
        return yaml.load(data['Value'], Loader=yaml.FullLoader)