Give AlbumentationsX a star on GitHub — it powers this leaderboard

Star on GitHub

nacos-sdk-python

Python client for Nacos.

Rank: #3118Downloads: 1,583,101 (30 days)Stars: 461Forks: 153

Description

nacos-sdk-python v3

English | 简体中文

A Python implementation of Nacos OpenAPI.

see: https://nacos.io/zh-cn/docs/open-API.html

Pypi Version License

Supported Python version:

Python 3.10+

Supported Nacos version

Supported Nacos version over 3.x

Note: AI Client feature requires Nacos server version 3.1.0 or above.

Installation

 pip install nacos-sdk-python

Client Configuration

from v2.nacos import NacosNamingService, NacosConfigService, NacosAIService, ClientConfigBuilder, GRPCConfig, \
    Instance, SubscribeServiceParam, RegisterInstanceParam, DeregisterInstanceParam, \
    BatchRegisterInstanceParam, GetServiceParam, ListServiceParam, ListInstanceParam, ConfigParam
    
client_config = (ClientConfigBuilder()
                 .access_key(os.getenv('NACOS_ACCESS_KEY'))
                 .secret_key(os.getenv('NACOS_SECRET_KEY'))
                 .server_address(os.getenv('NACOS_SERVER_ADDR', 'localhost:8848'))
                 .log_level('INFO')
                 .grpc_config(GRPCConfig(grpc_timeout=5000))
                 .build())
  • server_address - required - Nacos server address
  • access_key - The aliyun accessKey to authenticate.
  • secret_key - The aliyun secretKey to authenticate.
  • credentials_provider - The custom access key manager.
  • username - The username to authenticate.
  • password - The password to authenticate.
  • log_level - Log level | default: logging.INFO
  • cache_dir - cache dir path. | default: ~/nacos/cache
  • log_dir - log dir path. | default: ~/logs/nacos
  • namespace_id - namespace id. | default: ``
  • grpc_config - grpc config.
    • max_receive_message_length - max receive message length in grpc. | default: 100 * 1024 * 1024
    • max_keep_alive_ms - max keep alive ms in grpc. | default: 60 * 1000
    • initial_window_size - initial window size in grpc. | default: 10 * 1024 * 1024
    • initial_conn_window_size - initial connection window size in grpc. | default: 10 * 1024 * 1024
    • grpc_timeout - grpc timeout in milliseconds. | default: 3000
    • port_offset - gRPC port offset. The gRPC port = HTTP port + offset. | default: 1000
    • capability_negotiation_timeout - timeout for capability negotiation in milliseconds. | default: 5000
  • tls_config - tls config
    • enabled - whether enable tls.
    • ca_file - ca file path.
    • cert_file - cert file path.
    • key_file - key file path.
  • kms_config - aliyun kms config
    • enabled - whether enable aliyun kms.
    • endpoint - aliyun kms endpoint.
    • access_key - aliyun accessKey.
    • secret_key - aliyun secretKey.
    • password - aliyun kms password.

Config Client

config_client = await NacosConfigService.create_config_service(client_config)

config client common parameters

param: ConfigParam

  • param data_id Data id.
  • param group Group, use DEFAULT_GROUP if no group specified.
  • param content Config content.
  • param tag Config tag.
  • param app_name Application name.
  • param beta_ips Beta test ip address.
  • param cas_md5 MD5 check code.
  • param type Config type.
  • param src_user Source user.
  • param encrypted_data_key Encrypted data key.
  • param kms_key_id Kms encrypted data key id.
  • param usage_type Usage type.

Get Config

content = await config_client.get_config(ConfigParam(
            data_id=data_id,
            group=group
        ))
  • param ConfigParam config client common parameters. When getting configuration, it is necessary to specify the required data_id and group in param.
  • return Config content if success or an exception will be raised.

Get value of one config item following priority:

  • Step 1 - Get from local failover dir.

  • Step 2 - Get from one server until value is got or all servers tried.

    • Content will be saved to snapshot dir after got from server.
  • Step 3 - Get from snapshot dir.

Add Listener

async def config_listener(tenant, data_id, group, content):
    print("listen, tenant:{} data_id:{} group:{} content:{}".format(tenant, data_id, group, content))

await config_client.add_listener(dataID, groupName, config_listener)
  • param ConfigParam config client common parameters.
  • listener listener Configure listener, defined by the namespace_id、group、data_id、content.
  • return

Add Listener to a specified config item.

  • Once changes or deletion of the item happened, callback functions will be invoked.
  • If the item is already exists in server, callback functions will be invoked for once.
  • Callback functions are invoked from current process.

Remove Listener

await client.remove_listener(dataID, groupName, config_listener)
  • param ConfigParam config client common parameters.
  • return True if success or an exception will be raised.

Remove watcher from specified key.

Publish Config

res = await client.publish_config(ConfigParam(
            data_id=dataID,
            group=groupName,
            content="Hello world")
        )
  • param ConfigParam config client common parameters. When publishing configuration, it is necessary to specify the required data_id, group and content in param.
  • return True if success or an exception will be raised.

Publish one congfig data item to Nacos.

  • If the data key is not exist, create one first.
  • If the data key is exist, update to the content specified.
  • Content can not be set to None, if there is need to delete config item, use function remove instead.

Remove Config

res = await client.remove_config(ConfigParam(
            data_id=dataID,
            group=groupName
        ))
  • param ConfigParam config client common parameters.When removing configuration, it is necessary to specify the required data_id and group in param.
  • return True if success or an exception will be raised.

Remove one config data item from Nacos.

Stop Config Client

await client.shutdown()

Naming Client

naming_client = await NacosNamingService.create_naming_service(client_config)

Register Instance

response = await client.register_instance(
            request=RegisterInstanceParam(service_name='nacos.test.1', group_name='DEFAULT_GROUP', ip='1.1.1.1',
                port=7001, weight=1.0, cluster_name='c1', metadata={'a': 'b'},
                enabled=True,
                healthy=True, ephemeral=True))

Batch Register Instance

param1 = RegisterInstanceParam(service_name='nacos.test.1',
                                       group_name='DEFAULT_GROUP',
                                       ip='1.1.1.1',
                                       port=7001,
                                       weight=1.0,
                                       cluster_name='c1',
                                       metadata={'a': 'b'},
                                       enabled=True,
                                       healthy=True,
                                       ephemeral=True
                                       )
param2 = RegisterInstanceParam(service_name='nacos.test.1',
                               group_name='DEFAULT_GROUP',
                               ip='1.1.1.1',
                               port=7002,
                               weight=1.0,
                               cluster_name='c1',
                               metadata={'a': 'b'},
                               enabled=True,
                               healthy=True,
                               ephemeral=True
                               )
param3 = RegisterInstanceParam(service_name='nacos.test.1',
                               group_name='DEFAULT_GROUP',
                               ip='1.1.1.1',
                               port=7003,
                               weight=1.0,
                               cluster_name='c1',
                               metadata={'a': 'b'},
                               enabled=True,
                               healthy=False,
                               ephemeral=True
                               )
response = await client.batch_register_instances(
    request=BatchRegisterInstanceParam(service_name='nacos.test.1', group_name='DEFAULT_GROUP',
                                       instances=[param1, param2, param3]))

Deregister Instance

response = await client.deregister_instance(
          request=DeregisterInstanceParam(service_name='nacos.test.1', group_name='DEFAULT_GROUP', ip='1.1.1.1',
                                          port=7001, cluster_name='c1', ephemeral=True)
      )

Update Instance

response = await client.update_instance(
            request=RegisterInstanceParam(service_name='nacos.test.1', group_name='DEFAULT_GROUP', ip='1.1.1.1',
                                          port=7001, weight=2.0, cluster_name='c1', metadata={'a': 'b'},
                                          enabled=True,
                                          healthy=True, ephemeral=True))

Get Service

service = await client.get_service(
            GetServiceParam(service_name='nacos.test.1', group_name='DEFAULT_GROUP', cluster_name='c1'))

List Service

service_list = await client.list_services(ListServiceParam())

List Instance

instance_list = await client.list_instances(ListInstanceParam(service_name='nacos.test.1', healthy_only=True))
instance_list = await client.list_instances(ListInstanceParam(service_name='nacos.test.1', healthy_only=False))
instance_list = await client.list_instances(ListInstanceParam(service_name='nacos.test