0
# Client Infrastructure
1
2
Core client classes providing HTTP communication, request signing, error handling, and logging capabilities for all Tencent Cloud services. The infrastructure supports both service-specific clients and a generic client for dynamic API access.
3
4
## Capabilities
5
6
### Abstract Client Base Class
7
8
Foundation class providing common functionality for all Tencent Cloud service clients including HTTP communication, request signing, authentication, and logging.
9
10
```python { .api }
11
class AbstractClient:
12
def __init__(self, credential, region: str, profile = None):
13
"""
14
Initialize base client with connection parameters.
15
16
Parameters:
17
- credential: Credential object for authentication
18
- region (str): Tencent Cloud region (e.g., "ap-shanghai", "ap-beijing")
19
- profile (ClientProfile, optional): Client configuration profile
20
"""
21
22
def set_stream_logger(self, stream, level):
23
"""
24
Configure logging to output stream.
25
26
Parameters:
27
- stream: Output stream (e.g., sys.stdout, sys.stderr)
28
- level: Logging level (logging.DEBUG, logging.INFO, etc.)
29
"""
30
31
def set_file_logger(self, file_path: str, level):
32
"""
33
Configure rotating file logging.
34
35
Parameters:
36
- file_path (str): Log file directory path
37
- level: Logging level (logging.DEBUG, logging.INFO, etc.)
38
39
Note: Creates rotating logs with max 10 files, 512MB each
40
"""
41
42
def set_default_logger(self):
43
"""
44
Remove all log handlers and disable logging output.
45
"""
46
```
47
48
**Service Client Pattern:**
49
50
All service clients inherit from `AbstractClient` and follow this pattern:
51
52
```python
53
from tencentcloud.cvm.v20170312 import cvm_client, models
54
from tencentcloud.common import credential
55
56
# Initialize credentials
57
cred = credential.Credential("secret_id", "secret_key")
58
59
# Create service client
60
client = cvm_client.CvmClient(cred, "ap-shanghai")
61
62
# Optional: Configure logging
63
import sys
64
import logging
65
client.set_stream_logger(sys.stdout, logging.DEBUG)
66
67
# Make API calls
68
request = models.DescribeInstancesRequest()
69
response = client.DescribeInstances(request)
70
```
71
72
### Generic Common Client
73
74
Universal client for accessing any Tencent Cloud service API without importing service-specific modules. Useful for dynamic API access and rapid prototyping.
75
76
```python { .api }
77
class CommonClient(AbstractClient):
78
def __init__(self, service: str, version: str, credential, region: str, profile = None):
79
"""
80
Initialize generic client for any Tencent Cloud service.
81
82
Parameters:
83
- service (str): Service name (e.g., "cvm", "cbs", "vpc")
84
- version (str): API version (e.g., "2017-03-12")
85
- credential: Credential object for authentication
86
- region (str): Tencent Cloud region
87
- profile (ClientProfile, optional): Client configuration profile
88
"""
89
90
def call_json(self, action: str, params: dict, headers: dict = None):
91
"""
92
Call any service API action with JSON parameters.
93
94
Parameters:
95
- action (str): API action name (e.g., "DescribeInstances")
96
- params (dict): API parameters as dictionary
97
- headers (dict, optional): Custom HTTP headers
98
99
Returns:
100
dict: API response as dictionary
101
102
Raises:
103
TencentCloudSDKException: If API call fails
104
"""
105
106
def call(self, action: str, params: dict, headers: dict = None):
107
"""
108
Call any service API action (legacy method).
109
110
Parameters:
111
- action (str): API action name
112
- params (dict): API parameters as dictionary
113
- headers (dict, optional): Custom HTTP headers
114
115
Returns:
116
dict: API response as dictionary
117
118
Raises:
119
TencentCloudSDKException: If API call fails
120
"""
121
```
122
123
**Common Client Usage:**
124
125
```python
126
from tencentcloud.common.common_client import CommonClient
127
from tencentcloud.common import credential
128
129
# Initialize credentials
130
cred = credential.Credential("secret_id", "secret_key")
131
132
# Create generic client
133
client = CommonClient("cvm", "2017-03-12", cred, "ap-shanghai")
134
135
# Call API with JSON parameters
136
response = client.call_json("DescribeInstances", {
137
"Limit": 10,
138
"Filters": [
139
{
140
"Name": "zone",
141
"Values": ["ap-shanghai-1", "ap-shanghai-2"]
142
}
143
]
144
})
145
146
print(response["Response"]["InstanceSet"])
147
```
148
149
**Dynamic Service Access:**
150
151
```python
152
from tencentcloud.common.common_client import CommonClient
153
from tencentcloud.common import credential
154
155
def call_any_api(service, version, action, params, region="ap-shanghai"):
156
"""Utility function for dynamic API access."""
157
cred = credential.DefaultCredentialProvider().get_credential()
158
client = CommonClient(service, version, cred, region)
159
return client.call_json(action, params)
160
161
# Call different services dynamically
162
cvm_instances = call_any_api("cvm", "2017-03-12", "DescribeInstances", {"Limit": 5})
163
cbs_disks = call_any_api("cbs", "2017-03-12", "DescribeDisks", {"Limit": 10})
164
vpc_list = call_any_api("vpc", "2017-03-12", "DescribeVpcs", {})
165
```
166
167
### Client Configuration Integration
168
169
Both `AbstractClient` and `CommonClient` support comprehensive configuration through `ClientProfile`:
170
171
```python
172
from tencentcloud.common.profile.client_profile import ClientProfile
173
from tencentcloud.common.profile.http_profile import HttpProfile
174
from tencentcloud.common import retry
175
from tencentcloud.cvm.v20170312 import cvm_client
176
from tencentcloud.common import credential
177
import logging
178
import sys
179
180
# Configure HTTP settings
181
http_profile = HttpProfile()
182
http_profile.endpoint = "cvm.ap-shanghai.tencentcloudapi.com"
183
http_profile.reqMethod = "POST"
184
http_profile.reqTimeout = 30
185
http_profile.keepAlive = True
186
187
# Configure retry behavior
188
logger = logging.getLogger("retry")
189
logger.setLevel(logging.DEBUG)
190
logger.addHandler(logging.StreamHandler(sys.stderr))
191
192
# Configure client profile
193
client_profile = ClientProfile()
194
client_profile.httpProfile = http_profile
195
client_profile.signMethod = "TC3-HMAC-SHA256"
196
client_profile.language = "en-US"
197
client_profile.retryer = retry.StandardRetryer(max_attempts=3, logger=logger)
198
199
# Create client with configuration
200
cred = credential.DefaultCredentialProvider().get_credential()
201
client = cvm_client.CvmClient(cred, "ap-shanghai", client_profile)
202
```
203
204
### Advanced Client Features
205
206
**Custom Headers:**
207
208
```python
209
from tencentcloud.cvm.v20170312 import cvm_client, models
210
211
client = cvm_client.CvmClient(cred, "ap-shanghai")
212
request = models.DescribeInstancesRequest()
213
214
# Add custom headers for tracing
215
request.headers = {
216
"X-TC-TraceId": "ffe0c072-8a5d-4e17-8887-a8a60252abca",
217
"X-TC-Canary": "true"
218
}
219
220
response = client.DescribeInstances(request)
221
```
222
223
**Region Failover:**
224
225
```python
226
from tencentcloud.common.profile.client_profile import ClientProfile, RegionBreakerProfile
227
228
# Configure circuit breaker for region failover
229
region_breaker = RegionBreakerProfile(
230
backup_endpoint="ap-beijing.tencentcloudapi.com",
231
max_fail_num=3,
232
max_fail_percent=0.5,
233
window_interval=60,
234
timeout=30,
235
max_requests=3
236
)
237
238
client_profile = ClientProfile()
239
client_profile.disable_region_breaker = False
240
client_profile.region_breaker_profile = region_breaker
241
242
client = cvm_client.CvmClient(cred, "ap-shanghai", client_profile)
243
```
244
245
**Proxy Configuration:**
246
247
```python
248
from tencentcloud.common.profile.http_profile import HttpProfile
249
250
# Configure proxy
251
http_profile = HttpProfile()
252
http_profile.proxy = "http://username:password@proxy-server:port"
253
254
client_profile = ClientProfile()
255
client_profile.httpProfile = http_profile
256
257
client = cvm_client.CvmClient(cred, "ap-shanghai", client_profile)
258
```
259
260
## Client Lifecycle Management
261
262
**Single Client Instance:**
263
264
```python
265
# Reuse client instance for multiple requests
266
client = cvm_client.CvmClient(cred, "ap-shanghai")
267
268
for zone in ["ap-shanghai-1", "ap-shanghai-2", "ap-shanghai-3"]:
269
req = models.DescribeInstancesRequest()
270
filter_obj = models.Filter()
271
filter_obj.Name = "zone"
272
filter_obj.Values = [zone]
273
req.Filters = [filter_obj]
274
275
resp = client.DescribeInstances(req)
276
print(f"Zone {zone}: {resp.TotalCount} instances")
277
```
278
279
**Multi-Region Access:**
280
281
```python
282
regions = ["ap-shanghai", "ap-beijing", "ap-guangzhou"]
283
clients = {}
284
285
# Create clients for multiple regions
286
for region in regions:
287
clients[region] = cvm_client.CvmClient(cred, region)
288
289
# Use region-specific clients
290
for region, client in clients.items():
291
req = models.DescribeInstancesRequest()
292
resp = client.DescribeInstances(req)
293
print(f"Region {region}: {resp.TotalCount} instances")
294
```