A Python implementation of Nacos OpenAPI for service discovery, configuration management, and service management
npx @tessl/cli install tessl/pypi-nacos-sdk-python@2.0.00
# Nacos SDK Python
1
2
A comprehensive Python SDK for the Nacos service discovery and configuration management platform. This SDK provides both synchronous (v1) and asynchronous (v2) APIs for dynamic service discovery, configuration management, and service registration with Nacos clusters.
3
4
## Package Information
5
6
- **Package Name**: nacos-sdk-python
7
- **Language**: Python
8
- **Installation**: `pip install nacos-sdk-python`
9
- **Minimum Python Version**: Python 3.7+
10
11
## Core Imports
12
13
### Legacy V1 API (Synchronous)
14
15
```python
16
from nacos import NacosClient, NacosException, DEFAULTS, DEFAULT_GROUP_NAME
17
```
18
19
### Modern V2 API (Asynchronous)
20
21
```python
22
from v2.nacos import (
23
ClientConfig, ClientConfigBuilder,
24
NacosConfigService, NacosNamingService,
25
NacosException,
26
ConfigParam,
27
Instance, RegisterInstanceParam, DeregisterInstanceParam,
28
ListInstanceParam, SubscribeServiceParam
29
)
30
```
31
32
## Basic Usage
33
34
### V1 API - Simple Configuration Management
35
36
```python
37
from nacos import NacosClient
38
39
# Create client
40
client = NacosClient(
41
server_addresses="127.0.0.1:8848",
42
namespace="public",
43
username="nacos",
44
password="nacos"
45
)
46
47
# Get configuration
48
config = client.get_config("test-config", "DEFAULT_GROUP")
49
print(config)
50
51
# Publish configuration
52
client.publish_config("test-config", "DEFAULT_GROUP", "config content")
53
54
# Add configuration listener
55
def config_listener(args):
56
print(f"Configuration changed: {args}")
57
58
client.add_config_watcher("test-config", "DEFAULT_GROUP", config_listener)
59
```
60
61
### V2 API - Advanced Async Operations
62
63
```python
64
import asyncio
65
from v2.nacos import ClientConfig, NacosConfigService, ConfigParam
66
67
async def main():
68
# Create client configuration
69
client_config = ClientConfig(
70
server_addresses="127.0.0.1:8848",
71
namespace_id="public",
72
username="nacos",
73
password="nacos"
74
)
75
76
# Create config service
77
config_service = await NacosConfigService.create_config_service(client_config)
78
79
# Get configuration
80
param = ConfigParam(dataId="test-config", group="DEFAULT_GROUP")
81
config = await config_service.get_config(param)
82
print(config)
83
84
# Publish configuration
85
param.content = "new config content"
86
await config_service.publish_config(param)
87
88
# Shutdown
89
await config_service.shutdown()
90
91
asyncio.run(main())
92
```
93
94
## Architecture
95
96
Nacos SDK Python provides a dual-architecture approach:
97
98
- **V1 API (Legacy)**: Synchronous client with threading-based operations, suitable for simple use cases and backward compatibility
99
- **V2 API (Modern)**: Asynchronous client with GRPC support, advanced configuration options, and comprehensive data models
100
101
The V2 API introduces:
102
- **Configuration Service**: Async operations for configuration management with encryption, filtering, and caching
103
- **Naming Service**: Async operations for service discovery, registration, and health monitoring
104
- **Enhanced Models**: Pydantic-based data models for type safety and validation
105
- **GRPC Support**: High-performance communication protocol with connection pooling
106
- **Advanced Features**: KMS encryption, TLS security, batch operations, and comprehensive error handling
107
108
## Capabilities
109
110
### V1 Configuration Management (Synchronous)
111
112
Legacy synchronous API for configuration operations including get, publish, remove, and watch operations with basic authentication and namespace support.
113
114
```python { .api }
115
class NacosClient:
116
def __init__(self, server_addresses=None, endpoint=None, namespace=None,
117
ak=None, sk=None, username=None, password=None, **kwargs): ...
118
def get_config(self, data_id: str, group: str, timeout=None, no_snapshot=None) -> str: ...
119
def publish_config(self, data_id: str, group: str, content: str,
120
app_name=None, config_type=None, timeout=None) -> bool: ...
121
def remove_config(self, data_id: str, group: str, timeout=None) -> bool: ...
122
def add_config_watcher(self, data_id: str, group: str, cb, content=None): ...
123
def remove_config_watcher(self, data_id: str, group: str, cb, remove_all=False): ...
124
```
125
126
[V1 Configuration Management](./v1-config.md)
127
128
### V1 Service Discovery (Synchronous)
129
130
Legacy synchronous API for service registration, discovery, health checks, and subscription operations with basic clustering support.
131
132
```python { .api }
133
class NacosClient:
134
def add_naming_instance(self, service_name: str, ip: str, port: int,
135
cluster_name=None, weight=1.0, metadata=None, **kwargs) -> bool: ...
136
def remove_naming_instance(self, service_name: str, ip: str, port: int,
137
cluster_name=None, ephemeral=True, **kwargs) -> bool: ...
138
def list_naming_instance(self, service_name: str, clusters=None, namespace_id=None,
139
group_name=None, healthy_only=False) -> list: ...
140
def send_heartbeat(self, service_name: str, ip: str, port: int,
141
cluster_name=None, weight=1.0, metadata=None, ephemeral=True, **kwargs) -> dict: ...
142
def subscribe(self, service_name: str, listener_name: str, listener_fn,
143
cluster_names=None, **kwargs): ...
144
def unsubscribe(self, service_name: str, listener_name=None): ...
145
```
146
147
[V1 Service Discovery](./v1-naming.md)
148
149
### V2 Configuration Management (Asynchronous)
150
151
Modern asynchronous API for configuration operations with encryption, filtering, caching, and advanced error handling.
152
153
```python { .api }
154
class NacosConfigService:
155
@staticmethod
156
async def create_config_service(client_config: ClientConfig) -> 'NacosConfigService': ...
157
async def get_config(self, param: ConfigParam) -> str: ...
158
async def publish_config(self, param: ConfigParam) -> bool: ...
159
async def remove_config(self, param: ConfigParam): ...
160
async def add_listener(self, data_id: str, group: str, listener: Callable) -> None: ...
161
async def remove_listener(self, data_id: str, group: str, listener: Callable): ...
162
async def server_health(self) -> bool: ...
163
async def shutdown(self): ...
164
```
165
166
[V2 Configuration Management](./v2-config.md)
167
168
### V2 Service Discovery (Asynchronous)
169
170
Modern asynchronous API for service registration, discovery, batch operations, health monitoring, and subscription management with comprehensive data models.
171
172
```python { .api }
173
class NacosNamingService:
174
@staticmethod
175
async def create_naming_service(client_config: ClientConfig) -> 'NacosNamingService': ...
176
async def register_instance(self, request: RegisterInstanceParam) -> bool: ...
177
async def batch_register_instances(self, request: BatchRegisterInstanceParam) -> bool: ...
178
async def deregister_instance(self, request: DeregisterInstanceParam) -> bool: ...
179
async def list_instances(self, request: ListInstanceParam) -> List[Instance]: ...
180
async def get_service(self, request: GetServiceParam) -> Service: ...
181
async def list_services(self, request: ListServiceParam) -> ServiceList: ...
182
async def subscribe(self, request: SubscribeServiceParam) -> None: ...
183
async def unsubscribe(self, request: SubscribeServiceParam) -> None: ...
184
async def server_health(self) -> bool: ...
185
async def shutdown(self) -> None: ...
186
```
187
188
[V2 Service Discovery](./v2-naming.md)
189
190
### Client Configuration
191
192
Configuration classes for setting up Nacos clients with support for authentication, security, networking, and operational parameters.
193
194
```python { .api }
195
class ClientConfig:
196
def __init__(self, server_addresses=None, endpoint=None, namespace_id='',
197
context_path='', access_key=None, secret_key=None, username=None,
198
password=None, app_name='', app_key='', log_dir='', log_level=None,
199
log_rotation_backup_count=None, app_conn_labels=None, credentials_provider=None): ...
200
201
class ClientConfigBuilder:
202
def server_addresses(self, server_addresses: str) -> 'ClientConfigBuilder': ...
203
def namespace_id(self, namespace_id: str) -> 'ClientConfigBuilder': ...
204
def username(self, username: str) -> 'ClientConfigBuilder': ...
205
def password(self, password: str) -> 'ClientConfigBuilder': ...
206
def build(self) -> ClientConfig: ...
207
```
208
209
[Client Configuration](./client-config.md)
210
211
## Types
212
213
### V2 Data Models
214
215
```python { .api }
216
class Instance(BaseModel):
217
instanceId: str = ''
218
ip: str
219
port: int
220
weight: float = 1.0
221
healthy: bool = True
222
enabled: bool = True
223
ephemeral: bool = True
224
clusterName: str = ''
225
serviceName: str = ''
226
metadata: dict = {}
227
228
class ConfigParam(BaseModel):
229
dataId: str
230
group: str = 'DEFAULT_GROUP'
231
content: str = ''
232
type: str = ''
233
appName: str = ''
234
tag: str = ''
235
md5: str = ''
236
237
class RegisterInstanceParam(BaseModel):
238
ip: str
239
port: int
240
weight: float = 1.0
241
enabled: bool = True
242
healthy: bool = True
243
metadata: Dict[str, str] = {}
244
clusterName: str = ''
245
serviceName: str
246
groupName: str = 'DEFAULT_GROUP'
247
ephemeral: bool = True
248
249
class Service(BaseModel):
250
name: str
251
groupName: str
252
clusters: str
253
cacheMillis: int
254
hosts: List[Instance]
255
lastRefTime: int
256
checksum: str
257
allIPs: bool
258
reachProtectionThreshold: bool
259
260
class ServiceList(BaseModel):
261
count: int
262
services: List[str]
263
```
264
265
### Exception Classes
266
267
```python { .api }
268
class NacosException(Exception):
269
def __init__(self, error_code=None, message="An error occurred"): ...
270
271
# V1 Exception (legacy)
272
class NacosRequestException(NacosException): ...
273
```
274
275
### Constants
276
277
```python { .api }
278
DEFAULT_GROUP_NAME = "DEFAULT_GROUP"
279
DEFAULTS = {
280
"APP_NAME": "Nacos-SDK-Python",
281
"TIMEOUT": 3,
282
"PULLING_TIMEOUT": 30,
283
"PULLING_CONFIG_SIZE": 3000,
284
"CALLBACK_THREAD_NUM": 10,
285
"FAILOVER_BASE": "nacos-data/data",
286
"SNAPSHOT_BASE": "nacos-data/snapshot"
287
}
288
```