Nacos Python SDK

3.0.4 · active · verified Sat Apr 11

Python client for Nacos, a dynamic service discovery, configuration, and service management platform. It currently supports Nacos server versions 3.x and Python 3.10+. The library maintains a regular release cadence, with version 3.0.4 being the latest stable release.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to initialize the `NacosClient` and perform basic configuration publishing/retrieval and service registration/discovery. It's recommended to configure Nacos server addresses, namespace, and authentication credentials via environment variables for flexible deployment. For Nacos server 3.x and above, ensure the Nacos server is running and accessible.

import os
import nacos

# Configure Nacos server address and optional namespace/auth via environment variables
SERVER_ADDRESSES = os.environ.get('NACOS_SERVER_ADDR', '127.0.0.1:8848')
NAMESPACE_ID = os.environ.get('NACOS_NAMESPACE_ID', '') # e.g., 'public'
ACCESS_KEY = os.environ.get('NACOS_ACCESS_KEY', '')
SECRET_KEY = os.environ.get('NACOS_SECRET_KEY', '')

# Initialize Nacos Client
# For production, ensure access_key and secret_key are provided for authentication.
client = nacos.NacosClient(
    SERVER_ADDRESSES,
    namespace=NAMESPACE_ID,
    ak=ACCESS_KEY,
    sk=SECRET_KEY
)

# --- Configuration Service Example ---
data_id = "example_config"
group = "DEFAULT_GROUP"

# Publish a configuration
success = client.publish_config(data_id, group, "Hello from nacos-sdk-python!")
print(f"Published config: {success}")

# Get a configuration
config_content = client.get_config(data_id, group)
print(f"Retrieved config: {config_content}")

# --- Naming Service Example ---
service_name = "example_service"
service_ip = "127.0.0.1"
service_port = 8080

# Register an instance
registered = client.add_naming_instance(service_name, service_ip, service_port)
print(f"Registered service instance: {registered}")

# Query instances
instances = client.get_naming_instance(service_name, group_name=group)
print(f"Discovered instances: {instances}")

# Deregister an instance
deregistered = client.remove_naming_instance(service_name, service_ip, service_port)
print(f"Deregistered service instance: {deregistered}")

view raw JSON →