0
# Service Clients
1
2
Service-specific client classes for accessing Tencent Cloud APIs. All 242 service clients follow a consistent pattern and inherit from `AbstractClient`, providing unified authentication, error handling, and configuration while exposing service-specific API methods.
3
4
## Client Architecture
5
6
Each Tencent Cloud service provides a dedicated client class following the pattern:
7
- **Location**: `tencentcloud.{service}.{version}.{service}_client`
8
- **Class Name**: `{Service}Client` (e.g., `CvmClient`, `CbsClient`)
9
- **Base Class**: `AbstractClient`
10
- **Version Format**: `v{YYYYMMDD}` (e.g., `v20170312`)
11
12
## Capabilities
13
14
### Core Compute Services
15
16
#### Cloud Virtual Machine (CVM)
17
18
Complete virtual machine lifecycle management including instance operations, image management, snapshot handling, and security group configuration.
19
20
```python { .api }
21
class CvmClient(AbstractClient):
22
def __init__(self, credential, region: str, profile = None):
23
"""
24
Initialize CVM client for virtual machine management.
25
26
Parameters:
27
- credential: Authentication credential object
28
- region (str): Tencent Cloud region (e.g., "ap-shanghai")
29
- profile (ClientProfile, optional): Client configuration
30
"""
31
32
# Instance Management
33
def RunInstances(self, request) -> models.RunInstancesResponse:
34
"""Create and launch new CVM instances."""
35
36
def DescribeInstances(self, request) -> models.DescribeInstancesResponse:
37
"""Query CVM instance information."""
38
39
def StartInstances(self, request) -> models.StartInstancesResponse:
40
"""Start stopped CVM instances."""
41
42
def StopInstances(self, request) -> models.StopInstancesResponse:
43
"""Stop running CVM instances."""
44
45
def RebootInstances(self, request) -> models.RebootInstancesResponse:
46
"""Restart CVM instances."""
47
48
def TerminateInstances(self, request) -> models.TerminateInstancesResponse:
49
"""Terminate CVM instances permanently."""
50
51
def ResetInstance(self, request) -> models.ResetInstanceResponse:
52
"""Reinstall CVM instance operating system."""
53
54
def ResetInstancesPassword(self, request) -> models.ResetInstancesPasswordResponse:
55
"""Reset login passwords for CVM instances."""
56
57
def ResetInstancesType(self, request) -> models.ResetInstancesTypeResponse:
58
"""Change CVM instance specifications."""
59
60
def ModifyInstancesAttribute(self, request) -> models.ModifyInstancesAttributeResponse:
61
"""Modify CVM instance attributes."""
62
63
# Image Management
64
def CreateImage(self, request) -> models.CreateImageResponse:
65
"""Create custom images from CVM instances."""
66
67
def DescribeImages(self, request) -> models.DescribeImagesResponse:
68
"""Query available system and custom images."""
69
70
def ImportImage(self, request) -> models.ImportImageResponse:
71
"""Import external images to Tencent Cloud."""
72
73
def ModifyImageAttribute(self, request) -> models.ModifyImageAttributeResponse:
74
"""Modify image attributes."""
75
76
def DeleteImages(self, request) -> models.DeleteImagesResponse:
77
"""Delete custom images."""
78
79
# Snapshot Management
80
def CreateSnapshot(self, request) -> models.CreateSnapshotResponse:
81
"""Create disk snapshots for backup."""
82
83
def DescribeSnapshots(self, request) -> models.DescribeSnapshotsResponse:
84
"""Query disk snapshot information."""
85
86
def DeleteSnapshots(self, request) -> models.DeleteSnapshotsResponse:
87
"""Delete disk snapshots."""
88
89
# SSH Key Management
90
def CreateKeyPair(self, request) -> models.CreateKeyPairResponse:
91
"""Create SSH key pairs."""
92
93
def DescribeKeyPairs(self, request) -> models.DescribeKeyPairsResponse:
94
"""Query SSH key pair information."""
95
96
def ImportKeyPair(self, request) -> models.ImportKeyPairResponse:
97
"""Import existing SSH public keys."""
98
99
def DeleteKeyPairs(self, request) -> models.DeleteKeyPairsResponse:
100
"""Delete SSH key pairs."""
101
```
102
103
**CVM Usage Example:**
104
105
```python
106
from tencentcloud.cvm.v20170312 import cvm_client, models
107
from tencentcloud.common import credential
108
109
# Initialize client
110
cred = credential.DefaultCredentialProvider().get_credential()
111
client = cvm_client.CvmClient(cred, "ap-shanghai")
112
113
# Launch new instance
114
run_req = models.RunInstancesRequest()
115
run_req.ImageId = "img-9qabwvbn" # Ubuntu 20.04
116
run_req.InstanceType = "S5.MEDIUM2" # 2 vCPU, 2GB RAM
117
run_req.Placement = models.Placement()
118
run_req.Placement.Zone = "ap-shanghai-1"
119
run_req.InstanceCount = 1
120
121
response = client.RunInstances(run_req)
122
instance_id = response.InstanceIdSet[0]
123
print(f"Created instance: {instance_id}")
124
125
# Query instance status
126
desc_req = models.DescribeInstancesRequest()
127
desc_req.InstanceIds = [instance_id]
128
desc_response = client.DescribeInstances(desc_req)
129
130
instance = desc_response.InstanceSet[0]
131
print(f"Instance {instance.InstanceId} status: {instance.InstanceState}")
132
```
133
134
#### Cloud Block Storage (CBS)
135
136
Block storage volume management for persistent data storage, including disk creation, attachment, snapshot management, and performance optimization.
137
138
```python { .api }
139
class CbsClient(AbstractClient):
140
def __init__(self, credential, region: str, profile = None):
141
"""
142
Initialize CBS client for block storage management.
143
144
Parameters:
145
- credential: Authentication credential object
146
- region (str): Tencent Cloud region
147
- profile (ClientProfile, optional): Client configuration
148
"""
149
150
# Disk Management
151
def CreateDisks(self, request) -> models.CreateDisksResponse:
152
"""Create new cloud block storage disks."""
153
154
def DescribeDisks(self, request) -> models.DescribeDisksResponse:
155
"""Query cloud disk information."""
156
157
def AttachDisks(self, request) -> models.AttachDisksResponse:
158
"""Attach disks to CVM instances."""
159
160
def DetachDisks(self, request) -> models.DetachDisksResponse:
161
"""Detach disks from CVM instances."""
162
163
def ModifyDisksAttribute(self, request) -> models.ModifyDisksAttributeResponse:
164
"""Modify disk attributes."""
165
166
def ResizeDisk(self, request) -> models.ResizeDiskResponse:
167
"""Expand disk capacity."""
168
169
def DeleteDisks(self, request) -> models.DeleteDisksResponse:
170
"""Delete cloud disks."""
171
172
# Snapshot Management
173
def CreateSnapshot(self, request) -> models.CreateSnapshotResponse:
174
"""Create disk snapshots."""
175
176
def DescribeSnapshots(self, request) -> models.DescribeSnapshotsResponse:
177
"""Query snapshot information."""
178
179
def ModifySnapshotAttribute(self, request) -> models.ModifySnapshotAttributeResponse:
180
"""Modify snapshot attributes."""
181
182
def DeleteSnapshots(self, request) -> models.DeleteSnapshotsResponse:
183
"""Delete snapshots."""
184
```
185
186
**CBS Usage Example:**
187
188
```python
189
from tencentcloud.cbs.v20170312 import cbs_client, models
190
191
client = cbs_client.CbsClient(cred, "ap-shanghai")
192
193
# Create a new disk
194
create_req = models.CreateDisksRequest()
195
create_req.DiskType = "CLOUD_PREMIUM" # Premium SSD
196
create_req.DiskSize = 100 # 100GB
197
create_req.Placement = models.Placement()
198
create_req.Placement.Zone = "ap-shanghai-1"
199
create_req.DiskCount = 1
200
201
response = client.CreateDisks(create_req)
202
disk_id = response.DiskIdSet[0]
203
print(f"Created disk: {disk_id}")
204
205
# Attach disk to instance
206
attach_req = models.AttachDisksRequest()
207
attach_req.DiskIds = [disk_id]
208
attach_req.InstanceId = instance_id
209
210
client.AttachDisks(attach_req)
211
print(f"Attached disk {disk_id} to instance {instance_id}")
212
```
213
214
### Networking Services
215
216
#### Virtual Private Cloud (VPC)
217
218
Software-defined networking including VPC creation, subnet management, routing configuration, security groups, and network ACLs.
219
220
```python { .api }
221
class VpcClient(AbstractClient):
222
def __init__(self, credential, region: str, profile = None):
223
"""
224
Initialize VPC client for network management.
225
"""
226
227
# VPC Management
228
def CreateVpc(self, request) -> models.CreateVpcResponse:
229
"""Create virtual private cloud."""
230
231
def DescribeVpcs(self, request) -> models.DescribeVpcsResponse:
232
"""Query VPC information."""
233
234
def ModifyVpcAttribute(self, request) -> models.ModifyVpcAttributeResponse:
235
"""Modify VPC attributes."""
236
237
def DeleteVpc(self, request) -> models.DeleteVpcResponse:
238
"""Delete VPC."""
239
240
# Subnet Management
241
def CreateSubnet(self, request) -> models.CreateSubnetResponse:
242
"""Create VPC subnets."""
243
244
def DescribeSubnets(self, request) -> models.DescribeSubnetsResponse:
245
"""Query subnet information."""
246
247
def ModifySubnetAttribute(self, request) -> models.ModifySubnetAttributeResponse:
248
"""Modify subnet attributes."""
249
250
def DeleteSubnet(self, request) -> models.DeleteSubnetResponse:
251
"""Delete subnets."""
252
253
# Security Group Management
254
def CreateSecurityGroup(self, request) -> models.CreateSecurityGroupResponse:
255
"""Create security groups."""
256
257
def DescribeSecurityGroups(self, request) -> models.DescribeSecurityGroupsResponse:
258
"""Query security group information."""
259
260
def AuthorizeSecurityGroupPolicies(self, request) -> models.AuthorizeSecurityGroupPoliciesResponse:
261
"""Add security group rules."""
262
263
def RevokeSecurityGroupPolicies(self, request) -> models.RevokeSecurityGroupPoliciesResponse:
264
"""Remove security group rules."""
265
```
266
267
### Database Services
268
269
#### TencentDB for MySQL (CDB)
270
271
Managed MySQL database service with automated backups, monitoring, high availability, and performance optimization.
272
273
```python { .api }
274
class CdbClient(AbstractClient):
275
def __init__(self, credential, region: str, profile = None):
276
"""Initialize CDB client for MySQL database management."""
277
278
# Instance Management
279
def CreateDBInstance(self, request) -> models.CreateDBInstanceResponse:
280
"""Create MySQL database instances."""
281
282
def DescribeDBInstances(self, request) -> models.DescribeDBInstancesResponse:
283
"""Query database instance information."""
284
285
def RestartDBInstances(self, request) -> models.RestartDBInstancesResponse:
286
"""Restart database instances."""
287
288
def IsolateDBInstance(self, request) -> models.IsolateDBInstanceResponse:
289
"""Isolate database instance."""
290
291
# Database Management
292
def CreateDatabase(self, request) -> models.CreateDatabaseResponse:
293
"""Create databases within instance."""
294
295
def DescribeDatabases(self, request) -> models.DescribeDatabasesResponse:
296
"""Query database information."""
297
298
def DeleteDatabase(self, request) -> models.DeleteDatabaseResponse:
299
"""Delete databases."""
300
301
# Backup Management
302
def CreateBackup(self, request) -> models.CreateBackupResponse:
303
"""Create database backups."""
304
305
def DescribeBackups(self, request) -> models.DescribeBackupsResponse:
306
"""Query backup information."""
307
```
308
309
### AI and Machine Learning Services
310
311
#### Automatic Speech Recognition (ASR)
312
313
Real-time and batch speech recognition supporting multiple languages, audio formats, and customization options for various application scenarios.
314
315
```python { .api }
316
class AsrClient(AbstractClient):
317
def __init__(self, credential, region: str, profile = None):
318
"""Initialize ASR client for speech recognition."""
319
320
def SentenceRecognition(self, request) -> models.SentenceRecognitionResponse:
321
"""Recognize short audio clips (up to 1 minute)."""
322
323
def CreateRecTask(self, request) -> models.CreateRecTaskResponse:
324
"""Create long audio recognition task."""
325
326
def DescribeTaskStatus(self, request) -> models.DescribeTaskStatusResponse:
327
"""Query recognition task status."""
328
```
329
330
### Storage Services
331
332
#### Cloud Object Storage (COS)
333
334
S3-compatible object storage with global acceleration, lifecycle management, access control, and integration with other Tencent Cloud services.
335
336
```python { .api }
337
class CosClient(AbstractClient):
338
def __init__(self, credential, region: str, profile = None):
339
"""Initialize COS client for object storage."""
340
341
def PutBucket(self, request) -> models.PutBucketResponse:
342
"""Create storage buckets."""
343
344
def GetService(self, request) -> models.GetServiceResponse:
345
"""List all buckets."""
346
347
def PutObject(self, request) -> models.PutObjectResponse:
348
"""Upload objects to bucket."""
349
350
def GetObject(self, request) -> models.GetObjectResponse:
351
"""Download objects from bucket."""
352
353
def DeleteObject(self, request) -> models.DeleteObjectResponse:
354
"""Delete objects from bucket."""
355
```
356
357
## Service Client Usage Patterns
358
359
**Multi-Service Integration:**
360
361
```python
362
from tencentcloud.common import credential
363
from tencentcloud.cvm.v20170312 import cvm_client, models as cvm_models
364
from tencentcloud.cbs.v20170312 import cbs_client, models as cbs_models
365
from tencentcloud.vpc.v20170312 import vpc_client, models as vpc_models
366
367
# Initialize credentials once
368
cred = credential.DefaultCredentialProvider().get_credential()
369
370
# Create multiple service clients
371
cvm = cvm_client.CvmClient(cred, "ap-shanghai")
372
cbs = cbs_client.CbsClient(cred, "ap-shanghai")
373
vpc = vpc_client.VpcClient(cred, "ap-shanghai")
374
375
# Create VPC infrastructure
376
vpc_req = vpc_models.CreateVpcRequest()
377
vpc_req.VpcName = "MyVPC"
378
vpc_req.CidrBlock = "10.0.0.0/16"
379
vpc_response = vpc.CreateVpc(vpc_req)
380
vpc_id = vpc_response.Vpc.VpcId
381
382
# Create subnet
383
subnet_req = vpc_models.CreateSubnetRequest()
384
subnet_req.VpcId = vpc_id
385
subnet_req.SubnetName = "MySubnet"
386
subnet_req.CidrBlock = "10.0.1.0/24"
387
subnet_req.Zone = "ap-shanghai-1"
388
subnet_response = vpc.CreateSubnet(subnet_req)
389
subnet_id = subnet_response.Subnet.SubnetId
390
391
# Launch instance in VPC
392
run_req = cvm_models.RunInstancesRequest()
393
run_req.ImageId = "img-9qabwvbn"
394
run_req.InstanceType = "S5.MEDIUM2"
395
run_req.VirtualPrivateCloud = cvm_models.VirtualPrivateCloud()
396
run_req.VirtualPrivateCloud.VpcId = vpc_id
397
run_req.VirtualPrivateCloud.SubnetId = subnet_id
398
instance_response = cvm.RunInstances(run_req)
399
400
print(f"Created infrastructure: VPC {vpc_id}, Instance {instance_response.InstanceIdSet[0]}")
401
```
402
403
**Service Discovery and Dynamic Usage:**
404
405
```python
406
import importlib
407
from tencentcloud.common.common_client import CommonClient
408
409
def get_service_client(service_name, version, region="ap-shanghai"):
410
"""Dynamically create service client."""
411
try:
412
# Try specific service client first
413
module_path = f"tencentcloud.{service_name}.{version}"
414
client_module = importlib.import_module(f"{module_path}.{service_name}_client")
415
client_class = getattr(client_module, f"{service_name.capitalize()}Client")
416
417
cred = credential.DefaultCredentialProvider().get_credential()
418
return client_class(cred, region)
419
420
except (ImportError, AttributeError):
421
# Fall back to common client
422
cred = credential.DefaultCredentialProvider().get_credential()
423
return CommonClient(service_name, version.replace('v', ''), cred, region)
424
425
# Usage
426
cvm_client = get_service_client("cvm", "v20170312")
427
cbs_client = get_service_client("cbs", "v20170312")
428
unknown_client = get_service_client("newservice", "v20230101") # Falls back to CommonClient
429
```
430
431
**Error Handling Across Services:**
432
433
```python
434
from tencentcloud.common.exception.tencent_cloud_sdk_exception import TencentCloudSDKException
435
436
def safe_service_call(client, method_name, request):
437
"""Safely call any service method with error handling."""
438
try:
439
method = getattr(client, method_name)
440
response = method(request)
441
return response, None
442
443
except TencentCloudSDKException as err:
444
error_info = {
445
'code': err.get_code(),
446
'message': err.get_message(),
447
'request_id': err.get_request_id(),
448
'service': client.__class__.__name__,
449
'method': method_name
450
}
451
return None, error_info
452
453
except AttributeError:
454
return None, {'error': f'Method {method_name} not found on {client.__class__.__name__}'}
455
456
# Usage with any service
457
response, error = safe_service_call(cvm, "DescribeInstances", cvm_models.DescribeInstancesRequest())
458
if error:
459
print(f"API call failed: {error}")
460
else:
461
print(f"Success: {response.TotalCount} instances")
462
```