0
# Client Foundation
1
2
Abstract base classes providing the foundation for all Tencent Cloud service clients. Handles request building, signature generation, response processing, and error handling with support for multiple signature methods and various request formats.
3
4
## Capabilities
5
6
### Abstract Client Base Class
7
8
Foundation class that all Tencent Cloud service clients inherit from, providing core functionality for API communication.
9
10
```python { .api }
11
class AbstractClient:
12
def __init__(self, credential, region: str, profile: ClientProfile = None):
13
"""
14
Initialize abstract client.
15
16
Args:
17
credential: Credential object for authentication
18
region (str): Target region for API calls
19
profile (ClientProfile, optional): Client configuration profile
20
"""
21
22
def call_json(self, action: str, params: dict, headers: dict = None,
23
options: dict = None) -> dict:
24
"""
25
Call API with JSON parameters and return JSON response.
26
27
Args:
28
action (str): API action name (e.g., "DescribeInstances")
29
params (dict): Request parameters
30
headers (dict, optional): Custom request headers
31
options (dict, optional): Request options like {"SkipSign": False, "IsMultipart": False}
32
33
Returns:
34
dict: Parsed JSON response
35
36
Raises:
37
TencentCloudSDKException: On API errors or network issues
38
"""
39
40
def call_sse(self, action: str, params: dict, headers: dict = None,
41
options: dict = None):
42
"""
43
Call API with Server-Sent Events (SSE) response.
44
45
Args:
46
action (str): API action name
47
params (dict): Request parameters
48
headers (dict, optional): Custom request headers
49
options (dict, optional): Request options
50
51
Returns:
52
Generator: SSE event stream
53
54
Raises:
55
TencentCloudSDKException: On API errors or network issues
56
"""
57
58
def call_octet_stream(self, action: str, headers: dict, body: bytes,
59
options: dict = None) -> dict:
60
"""
61
Call API with application/octet-stream content type.
62
63
Note: Only works with TC3-HMAC-SHA256 signature method and POST requests.
64
65
Args:
66
action (str): API action name
67
headers (dict): Request headers
68
body (bytes): Request body as bytes
69
options (dict, optional): Request options
70
71
Returns:
72
dict: Parsed JSON response
73
74
Raises:
75
TencentCloudSDKException: On signature method or request method errors
76
"""
77
78
def call(self, action: str, params: dict, options: dict = None,
79
headers: dict = None) -> str:
80
"""
81
Call API and return raw response content.
82
83
Args:
84
action (str): API action name
85
params (dict): Request parameters
86
options (dict, optional): Request options
87
headers (dict, optional): Custom request headers
88
89
Returns:
90
str: Raw response content
91
92
Raises:
93
TencentCloudSDKException: On API errors or network issues
94
"""
95
96
def set_stream_logger(self, stream = None, level: int = None,
97
log_format: str = None) -> None:
98
"""
99
Add a stream handler for logging.
100
101
Args:
102
stream: Output stream (e.g., sys.stdout, sys.stderr)
103
level (int, optional): Logging level (e.g., logging.DEBUG)
104
log_format (str, optional): Log message format
105
"""
106
107
def set_file_logger(self, file_path: str, level: int = None,
108
log_format: str = None) -> None:
109
"""
110
Add a file handler for logging.
111
112
Args:
113
file_path (str): Path to log file
114
level (int, optional): Logging level (e.g., logging.INFO)
115
log_format (str, optional): Log message format
116
"""
117
118
def set_default_logger(self) -> None:
119
"""Reset to default (empty) log handler."""
120
```
121
122
### Common Client for All Services
123
124
General-purpose client that can be used with any Tencent Cloud service without requiring service-specific SDKs.
125
126
```python { .api }
127
class CommonClient(AbstractClient):
128
def __init__(self, service: str, version: str, credential, region: str,
129
profile: ClientProfile = None):
130
"""
131
Create common client for any Tencent Cloud service.
132
133
Args:
134
service (str): Service name (e.g., "cvm", "cos", "vpc")
135
version (str): API version (e.g., "2017-03-12")
136
credential: Credential object for authentication
137
region (str): Target region
138
profile (ClientProfile, optional): Client configuration
139
140
Raises:
141
TencentCloudSDKException: If required parameters are missing
142
"""
143
```
144
145
### Abstract Model Base Class
146
147
Base class for all API request and response models with serialization support.
148
149
```python { .api }
150
class AbstractModel:
151
@property
152
def headers(self) -> dict:
153
"""
154
Get model headers.
155
156
Returns:
157
dict: Model headers
158
"""
159
160
@headers.setter
161
def headers(self, headers: dict) -> None:
162
"""
163
Set model headers.
164
165
Args:
166
headers (dict): Headers to set
167
"""
168
169
def to_json_string(self, *args, **kwargs) -> str:
170
"""
171
Serialize model to JSON string.
172
173
Args:
174
*args: Additional positional arguments for json.dumps
175
**kwargs: Additional keyword arguments for json.dumps
176
177
Returns:
178
str: JSON string representation
179
"""
180
181
def from_json_string(self, jsonStr: str) -> None:
182
"""
183
Deserialize JSON string to populate model.
184
185
Args:
186
jsonStr (str): JSON formatted string
187
"""
188
```
189
190
## Usage Examples
191
192
### Using Common Client
193
194
```python
195
from tencentcloud.common.credential import Credential
196
from tencentcloud.common.common_client import CommonClient
197
from tencentcloud.common.profile.client_profile import ClientProfile
198
from tencentcloud.common.profile.http_profile import HttpProfile
199
200
# Create credentials
201
cred = Credential("your-secret-id", "your-secret-key")
202
203
# Configure profiles
204
http_profile = HttpProfile()
205
http_profile.endpoint = "cvm.tencentcloudapi.com"
206
207
client_profile = ClientProfile()
208
client_profile.httpProfile = http_profile
209
210
# Create common client for CVM service
211
client = CommonClient("cvm", "2017-03-12", cred, "ap-guangzhou", client_profile)
212
213
# Call API using JSON
214
response = client.call_json("DescribeInstances", {
215
"Limit": 10,
216
"Offset": 0
217
})
218
print("Instances:", response["Response"]["InstanceSet"])
219
220
# Call with custom headers
221
headers = {"X-TC-TraceId": "custom-trace-id"}
222
response = client.call_json("DescribeRegions", {}, headers=headers)
223
```
224
225
### Using Abstract Client (Custom Service Client)
226
227
```python
228
from tencentcloud.common.abstract_client import AbstractClient
229
from tencentcloud.common.credential import Credential
230
231
class CustomServiceClient(AbstractClient):
232
def __init__(self, credential, region, profile=None):
233
super().__init__(credential, region, profile)
234
self._service = "custom-service"
235
self._apiVersion = "2021-01-01"
236
237
# Create custom service client
238
cred = Credential("your-secret-id", "your-secret-key")
239
client = CustomServiceClient(cred, "ap-guangzhou")
240
241
# Make API calls
242
response = client.call_json("CustomAction", {"param": "value"})
243
```
244
245
### Working with Models
246
247
```python
248
from tencentcloud.common.abstract_model import AbstractModel
249
import json
250
251
class MyModel(AbstractModel):
252
def __init__(self):
253
self.field1 = None
254
self.field2 = None
255
256
# Create model
257
model = MyModel()
258
model.field1 = "value1"
259
model.field2 = "value2"
260
261
# Serialize to JSON
262
json_str = model.to_json_string()
263
print(json_str)
264
265
# Deserialize from JSON
266
new_model = MyModel()
267
new_model.from_json_string('{"field1": "new_value1", "field2": "new_value2"}')
268
```
269
270
### Server-Sent Events (SSE)
271
272
```python
273
from tencentcloud.common.common_client import CommonClient
274
275
# Create client (same as above)
276
client = CommonClient("service", "version", cred, "region")
277
278
# Call SSE endpoint
279
for event in client.call_sse("StreamingAction", {"param": "value"}):
280
if "data" in event:
281
print("Received data:", event["data"])
282
```
283
284
### Binary Data Upload
285
286
```python
287
from tencentcloud.common.common_client import CommonClient
288
289
# Create client
290
client = CommonClient("service", "version", cred, "region")
291
292
# Upload binary data
293
with open("file.bin", "rb") as f:
294
binary_data = f.read()
295
296
headers = {"Content-Type": "application/octet-stream"}
297
response = client.call_octet_stream("UploadBinary", headers, binary_data)
298
```
299
300
### Custom Logging
301
302
```python
303
import sys
304
import logging
305
from tencentcloud.common.common_client import CommonClient
306
307
# Create client
308
client = CommonClient("cvm", "2017-03-12", cred, "ap-guangzhou")
309
310
# Add stream logging
311
client.set_stream_logger(sys.stdout, logging.DEBUG)
312
313
# Add file logging
314
client.set_file_logger("/tmp/sdk.log", logging.INFO)
315
316
# API calls will now be logged
317
response = client.call_json("DescribeInstances", {})
318
```
319
320
### Error Handling
321
322
```python
323
from tencentcloud.common.exception.tencent_cloud_sdk_exception import TencentCloudSDKException
324
from tencentcloud.common.common_client import CommonClient
325
326
client = CommonClient("cvm", "2017-03-12", cred, "ap-guangzhou")
327
328
try:
329
response = client.call_json("DescribeInstances", {})
330
except TencentCloudSDKException as e:
331
print(f"API Error: {e.get_code()}")
332
print(f"Message: {e.get_message()}")
333
print(f"Request ID: {e.get_request_id()}")
334
except Exception as e:
335
print(f"Other error: {e}")
336
```