Python 集成 Nacos 配置中心

Python 集成 Nacos 配置中心

下载 Nacos 官方 pyhton 库

pip install nacos-sdk-python
# 指定国内阿里云镜像源
pip3 install nacos-sdk-python -i http://mirrors.aliyun.com/pypi/simple/ --trusted-host mirrors.aliyun.com

配置 Nacos 相关信息

Global:
  nacos:
    port: '8848'
    ip: '127.0.0.1'
    username: 'nacos'
    password: '123456'
    namespace: 'test'
    group: 'test'
    data_id: 'test'
  • 这里通过 env.yaml 指定相关配置信息定义环境变量配置文件

代码逻辑

from nacos import NacosClient
import yaml
import os
import json



# 使用 pyyaml 模块,把从配置中心获取的 yaml 数据转为 json 数据
def get_config():
    config = load_config('../config/env.yaml')
    client = NacosClient(config['Global']['nacos']['ip'] + ':' + config['Global']['nacos']['port'],
                         namespace=config['Global']['nacos']['namespace'],
                         username=config['Global']['nacos']['username'],
                         password=config['Global']['nacos']['password'])
    data_id = config['Global']['nacos']['data_id']
    group = config['Global']['nacos']['group']
    config_info = client.get_config(data_id, group)
    if isinstance(config_info,bytes):
        str_config_info = config_info.decode()
    else:
        str_config_info = config_info
    dict_config_info = yaml.load(str_config_info,Loader=yaml.FullLoader)
    json_data = json.dumps(dict_config_info)
    print(json_data)
    return json_data


# 加载 yaml 文件里的信息
def load_config(file_path):
    """
    Load config from yml/yaml file.
    Args:
        file_path (str): Path of the config file to be loaded.
    Returns: global config
    """
    _, ext = os.path.splitext(file_path)
    assert ext in ['.yml', '.yaml'], "only support yaml files for now"
    config = yaml.load(open(file_path, 'rb'), Loader=yaml.Loader)
    return config

# 测试
if __name__ == '__main__':
    get_config()

运行结果

  • Nacos 控制台配置文件内容

Python 集成 Nacos 配置中心_第1张图片

  • 获取的 Nacos 中的配置信息

Python 集成 Nacos 配置中心_第2张图片

你可能感兴趣的:(Python,python)