python请求nacos配置

pip install nacos-sdk-python

{
    "name": "Alice",
    "age": 27,
    "is_student": "False",
    "courses": ["Math", "Science"],
    "address": {
        "street": "123 Wonderland Ave",
        "city": "Rabbit Hole"
    }
}
from nacos import NacosClient
import time
import json

# 初始化Nacos客户端,包含鉴权信息
nacos_client = NacosClient(
    'http://172.30.64.10:8848',  # Nacos 服务器地址
    namespace='hik',  # 如果有命名空间 ID,请指定
    username='nacos',  # Nacos 用户名
    password='nacos'  # Nacos 密码
)

# 获取配置
data_id = 'hik.api.service'
group = 'HIK_GROUP'  # 如果没有特别设置,默认是这个组
config = nacos_client.get_config(data_id, group)

print(f"Current config: {config}")


# 监听配置变化
def config_change_callback(change_info):
    try:
        # 打印更新变化完整数据信息,数据类型为字典
        print('数据产生变化:', change_info)
        # 把raw_content从change_info字典取出
        # 取出后为字符类型,再次转换成字典
        # 并从字典中取出AGE的信息
        print(json.loads(change_info['raw_content'])['age'])
        # 从字典里按层级取出street的值
        print(json.loads(change_info['raw_content'])['address']['street'])

        # 从address这个层级取出所有的值
        for key in json.loads(change_info['raw_content'])['address'].keys():
            print('address值:', key, json.loads(change_info['raw_content'])['address'][key])

    except json.JSONDecodeError as e:
        print(f"Failed to decode JSON: {e}")


if __name__ == "__main__":
    # 添加配置监听器
    nacos_client.add_config_watcher(data_id, group, config_change_callback)

    # 保持程序运行以持续监听配置变化
    try:
        while True:
            time.sleep(60)
    except KeyboardInterrupt:
        pass