0
# V1 Configuration Management (Synchronous)
1
2
Legacy synchronous API for Nacos configuration operations. This API provides basic configuration management functionality using HTTP requests with threading-based operations for backward compatibility.
3
4
## Capabilities
5
6
### Client Initialization
7
8
Create a synchronous Nacos client for configuration operations.
9
10
```python { .api }
11
class NacosClient:
12
def __init__(self, server_addresses=None, endpoint=None, namespace=None, ak=None, sk=None,
13
username=None, password=None, app_name=None, app_key=None, log_dir=None,
14
log_level=None, log_rotation_backup_count=None, **kwargs):
15
"""
16
Initialize Nacos client.
17
18
Args:
19
server_addresses (str): Comma-separated list of Nacos server addresses
20
endpoint (str): Address server endpoint for dynamic server discovery
21
namespace (str): Nacos namespace ID
22
ak (str): Access key for authentication
23
sk (str): Secret key for authentication
24
username (str): Username for authentication
25
password (str): Password for authentication
26
app_name (str): Application name
27
app_key (str): Application key
28
log_dir (str): Directory for log files
29
log_level: Logging level
30
log_rotation_backup_count (int): Number of backup log files
31
"""
32
```
33
34
Usage example:
35
36
```python
37
from nacos import NacosClient
38
39
# Basic client with server addresses
40
client = NacosClient(server_addresses="127.0.0.1:8848,127.0.0.1:8849")
41
42
# Client with authentication
43
client = NacosClient(
44
server_addresses="127.0.0.1:8848",
45
namespace="production",
46
username="nacos",
47
password="nacos"
48
)
49
50
# Client with access key authentication
51
client = NacosClient(
52
server_addresses="127.0.0.1:8848",
53
ak="your-access-key",
54
sk="your-secret-key"
55
)
56
```
57
58
### Get Configuration
59
60
Retrieve configuration values from Nacos server.
61
62
```python { .api }
63
def get_config(self, data_id: str, group: str, timeout=None, no_snapshot=None) -> str:
64
"""
65
Get configuration from Nacos server.
66
67
Args:
68
data_id (str): Configuration data ID
69
group (str): Configuration group
70
timeout (int, optional): Request timeout in seconds
71
no_snapshot (bool, optional): Disable local snapshot fallback
72
73
Returns:
74
str: Configuration content
75
76
Raises:
77
NacosException: If data_id or group is invalid
78
NacosRequestException: If request fails
79
"""
80
```
81
82
Usage example:
83
84
```python
85
# Get configuration
86
config = client.get_config("database.config", "DEFAULT_GROUP")
87
print(config)
88
89
# Get with custom timeout
90
config = client.get_config("database.config", "DEFAULT_GROUP", timeout=10)
91
92
# Get with snapshot disabled
93
config = client.get_config("database.config", "DEFAULT_GROUP", no_snapshot=True)
94
```
95
96
### Publish Configuration
97
98
Publish or update configuration values on Nacos server.
99
100
```python { .api }
101
def publish_config(self, data_id: str, group: str, content: str, app_name=None,
102
config_type=None, timeout=None) -> bool:
103
"""
104
Publish configuration to Nacos server.
105
106
Args:
107
data_id (str): Configuration data ID
108
group (str): Configuration group
109
content (str): Configuration content
110
app_name (str, optional): Application name
111
config_type (str, optional): Configuration type (e.g., 'json', 'yaml', 'properties')
112
timeout (int, optional): Request timeout in seconds
113
114
Returns:
115
bool: True if successful
116
117
Raises:
118
NacosException: If data_id or group is invalid
119
NacosRequestException: If request fails
120
"""
121
```
122
123
Usage example:
124
125
```python
126
# Publish simple configuration
127
client.publish_config("database.config", "DEFAULT_GROUP", "host=localhost\nport=3306")
128
129
# Publish JSON configuration
130
config_content = '{"host": "localhost", "port": 3306}'
131
client.publish_config("database.config", "DEFAULT_GROUP", config_content, config_type="json")
132
133
# Publish with app name
134
client.publish_config("database.config", "DEFAULT_GROUP", config_content, app_name="my-app")
135
```
136
137
### Remove Configuration
138
139
Remove configuration from Nacos server.
140
141
```python { .api }
142
def remove_config(self, data_id: str, group: str, timeout=None) -> bool:
143
"""
144
Remove configuration from Nacos server.
145
146
Args:
147
data_id (str): Configuration data ID
148
group (str): Configuration group
149
timeout (int, optional): Request timeout in seconds
150
151
Returns:
152
bool: True if successful
153
154
Raises:
155
NacosException: If data_id or group is invalid
156
NacosRequestException: If request fails
157
"""
158
```
159
160
Usage example:
161
162
```python
163
# Remove configuration
164
success = client.remove_config("database.config", "DEFAULT_GROUP")
165
if success:
166
print("Configuration removed successfully")
167
```
168
169
### Configuration Watchers
170
171
Add and manage configuration change listeners.
172
173
```python { .api }
174
def add_config_watcher(self, data_id: str, group: str, cb, content=None):
175
"""
176
Add configuration change listener.
177
178
Args:
179
data_id (str): Configuration data ID
180
group (str): Configuration group
181
cb (callable): Callback function to handle configuration changes
182
content (str, optional): Initial content for comparison
183
"""
184
185
def add_config_watchers(self, data_id: str, group: str, cb_list, content=None):
186
"""
187
Add multiple configuration change listeners.
188
189
Args:
190
data_id (str): Configuration data ID
191
group (str): Configuration group
192
cb_list (list): List of callback functions
193
content (str, optional): Initial content for comparison
194
"""
195
196
def remove_config_watcher(self, data_id: str, group: str, cb, remove_all=False):
197
"""
198
Remove configuration change listener.
199
200
Args:
201
data_id (str): Configuration data ID
202
group (str): Configuration group
203
cb (callable): Callback function to remove
204
remove_all (bool): Remove all listeners for this config
205
"""
206
```
207
208
Usage example:
209
210
```python
211
def config_change_handler(args):
212
print(f"Configuration changed: {args}")
213
# Handle configuration change
214
215
# Add single listener
216
client.add_config_watcher("database.config", "DEFAULT_GROUP", config_change_handler)
217
218
# Add multiple listeners
219
def backup_handler(args):
220
print(f"Backup handler: {args}")
221
222
client.add_config_watchers("database.config", "DEFAULT_GROUP",
223
[config_change_handler, backup_handler])
224
225
# Remove specific listener
226
client.remove_config_watcher("database.config", "DEFAULT_GROUP", config_change_handler)
227
228
# Remove all listeners
229
client.remove_config_watcher("database.config", "DEFAULT_GROUP", None, remove_all=True)
230
```
231
232
### Batch Configuration Operations
233
234
Retrieve multiple configurations in a single request.
235
236
```python { .api }
237
def get_configs(self, timeout=None, no_snapshot=None, group="", page_no=1, page_size=1000) -> dict:
238
"""
239
Get multiple configurations with pagination.
240
241
Args:
242
timeout (int, optional): Request timeout in seconds
243
no_snapshot (bool, optional): Disable local snapshot fallback
244
group (str): Configuration group filter
245
page_no (int): Page number (1-based)
246
page_size (int): Number of configurations per page
247
248
Returns:
249
dict: Dictionary containing configurations and pagination info
250
"""
251
```
252
253
Usage example:
254
255
```python
256
# Get all configurations
257
configs = client.get_configs()
258
print(f"Total configs: {configs.get('totalCount', 0)}")
259
260
# Get configurations with pagination
261
configs = client.get_configs(page_no=1, page_size=50)
262
for config in configs.get('pageItems', []):
263
print(f"Config: {config['dataId']} = {config['content']}")
264
265
# Get configurations from specific group
266
configs = client.get_configs(group="DEFAULT_GROUP")
267
```
268
269
## Error Handling
270
271
```python { .api }
272
class NacosException(Exception):
273
"""Base exception for Nacos operations."""
274
pass
275
276
class NacosRequestException(NacosException):
277
"""Exception for HTTP request failures."""
278
pass
279
```
280
281
Common error scenarios:
282
283
```python
284
from nacos import NacosClient, NacosException, NacosRequestException
285
286
try:
287
client = NacosClient(server_addresses="127.0.0.1:8848")
288
config = client.get_config("test-config", "DEFAULT_GROUP")
289
except NacosRequestException as e:
290
print(f"Request failed: {e}")
291
except NacosException as e:
292
print(f"Nacos error: {e}")
293
except Exception as e:
294
print(f"Unexpected error: {e}")
295
```
296
297
## Constants and Defaults
298
299
```python { .api }
300
DEFAULT_GROUP_NAME = "DEFAULT_GROUP"
301
DEFAULTS = {
302
"APP_NAME": "Nacos-SDK-Python",
303
"TIMEOUT": 3,
304
"PULLING_TIMEOUT": 30,
305
"PULLING_CONFIG_SIZE": 3000,
306
"CALLBACK_THREAD_NUM": 10,
307
"FAILOVER_BASE": "nacos-data/data",
308
"SNAPSHOT_BASE": "nacos-data/snapshot"
309
}
310
```