Comprehensive Python SDK for integrating with Tencent Cloud services, supporting 240+ cloud services with authentication, error handling, and retry mechanisms.
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.
Each Tencent Cloud service provides a dedicated client class following the pattern:
tencentcloud.{service}.{version}.{service}_client{Service}Client (e.g., CvmClient, CbsClient)AbstractClientv{YYYYMMDD} (e.g., v20170312)Complete virtual machine lifecycle management including instance operations, image management, snapshot handling, and security group configuration.
class CvmClient(AbstractClient):
def __init__(self, credential, region: str, profile = None):
"""
Initialize CVM client for virtual machine management.
Parameters:
- credential: Authentication credential object
- region (str): Tencent Cloud region (e.g., "ap-shanghai")
- profile (ClientProfile, optional): Client configuration
"""
# Instance Management
def RunInstances(self, request) -> models.RunInstancesResponse:
"""Create and launch new CVM instances."""
def DescribeInstances(self, request) -> models.DescribeInstancesResponse:
"""Query CVM instance information."""
def StartInstances(self, request) -> models.StartInstancesResponse:
"""Start stopped CVM instances."""
def StopInstances(self, request) -> models.StopInstancesResponse:
"""Stop running CVM instances."""
def RebootInstances(self, request) -> models.RebootInstancesResponse:
"""Restart CVM instances."""
def TerminateInstances(self, request) -> models.TerminateInstancesResponse:
"""Terminate CVM instances permanently."""
def ResetInstance(self, request) -> models.ResetInstanceResponse:
"""Reinstall CVM instance operating system."""
def ResetInstancesPassword(self, request) -> models.ResetInstancesPasswordResponse:
"""Reset login passwords for CVM instances."""
def ResetInstancesType(self, request) -> models.ResetInstancesTypeResponse:
"""Change CVM instance specifications."""
def ModifyInstancesAttribute(self, request) -> models.ModifyInstancesAttributeResponse:
"""Modify CVM instance attributes."""
# Image Management
def CreateImage(self, request) -> models.CreateImageResponse:
"""Create custom images from CVM instances."""
def DescribeImages(self, request) -> models.DescribeImagesResponse:
"""Query available system and custom images."""
def ImportImage(self, request) -> models.ImportImageResponse:
"""Import external images to Tencent Cloud."""
def ModifyImageAttribute(self, request) -> models.ModifyImageAttributeResponse:
"""Modify image attributes."""
def DeleteImages(self, request) -> models.DeleteImagesResponse:
"""Delete custom images."""
# Snapshot Management
def CreateSnapshot(self, request) -> models.CreateSnapshotResponse:
"""Create disk snapshots for backup."""
def DescribeSnapshots(self, request) -> models.DescribeSnapshotsResponse:
"""Query disk snapshot information."""
def DeleteSnapshots(self, request) -> models.DeleteSnapshotsResponse:
"""Delete disk snapshots."""
# SSH Key Management
def CreateKeyPair(self, request) -> models.CreateKeyPairResponse:
"""Create SSH key pairs."""
def DescribeKeyPairs(self, request) -> models.DescribeKeyPairsResponse:
"""Query SSH key pair information."""
def ImportKeyPair(self, request) -> models.ImportKeyPairResponse:
"""Import existing SSH public keys."""
def DeleteKeyPairs(self, request) -> models.DeleteKeyPairsResponse:
"""Delete SSH key pairs."""CVM Usage Example:
from tencentcloud.cvm.v20170312 import cvm_client, models
from tencentcloud.common import credential
# Initialize client
cred = credential.DefaultCredentialProvider().get_credential()
client = cvm_client.CvmClient(cred, "ap-shanghai")
# Launch new instance
run_req = models.RunInstancesRequest()
run_req.ImageId = "img-9qabwvbn" # Ubuntu 20.04
run_req.InstanceType = "S5.MEDIUM2" # 2 vCPU, 2GB RAM
run_req.Placement = models.Placement()
run_req.Placement.Zone = "ap-shanghai-1"
run_req.InstanceCount = 1
response = client.RunInstances(run_req)
instance_id = response.InstanceIdSet[0]
print(f"Created instance: {instance_id}")
# Query instance status
desc_req = models.DescribeInstancesRequest()
desc_req.InstanceIds = [instance_id]
desc_response = client.DescribeInstances(desc_req)
instance = desc_response.InstanceSet[0]
print(f"Instance {instance.InstanceId} status: {instance.InstanceState}")Block storage volume management for persistent data storage, including disk creation, attachment, snapshot management, and performance optimization.
class CbsClient(AbstractClient):
def __init__(self, credential, region: str, profile = None):
"""
Initialize CBS client for block storage management.
Parameters:
- credential: Authentication credential object
- region (str): Tencent Cloud region
- profile (ClientProfile, optional): Client configuration
"""
# Disk Management
def CreateDisks(self, request) -> models.CreateDisksResponse:
"""Create new cloud block storage disks."""
def DescribeDisks(self, request) -> models.DescribeDisksResponse:
"""Query cloud disk information."""
def AttachDisks(self, request) -> models.AttachDisksResponse:
"""Attach disks to CVM instances."""
def DetachDisks(self, request) -> models.DetachDisksResponse:
"""Detach disks from CVM instances."""
def ModifyDisksAttribute(self, request) -> models.ModifyDisksAttributeResponse:
"""Modify disk attributes."""
def ResizeDisk(self, request) -> models.ResizeDiskResponse:
"""Expand disk capacity."""
def DeleteDisks(self, request) -> models.DeleteDisksResponse:
"""Delete cloud disks."""
# Snapshot Management
def CreateSnapshot(self, request) -> models.CreateSnapshotResponse:
"""Create disk snapshots."""
def DescribeSnapshots(self, request) -> models.DescribeSnapshotsResponse:
"""Query snapshot information."""
def ModifySnapshotAttribute(self, request) -> models.ModifySnapshotAttributeResponse:
"""Modify snapshot attributes."""
def DeleteSnapshots(self, request) -> models.DeleteSnapshotsResponse:
"""Delete snapshots."""CBS Usage Example:
from tencentcloud.cbs.v20170312 import cbs_client, models
client = cbs_client.CbsClient(cred, "ap-shanghai")
# Create a new disk
create_req = models.CreateDisksRequest()
create_req.DiskType = "CLOUD_PREMIUM" # Premium SSD
create_req.DiskSize = 100 # 100GB
create_req.Placement = models.Placement()
create_req.Placement.Zone = "ap-shanghai-1"
create_req.DiskCount = 1
response = client.CreateDisks(create_req)
disk_id = response.DiskIdSet[0]
print(f"Created disk: {disk_id}")
# Attach disk to instance
attach_req = models.AttachDisksRequest()
attach_req.DiskIds = [disk_id]
attach_req.InstanceId = instance_id
client.AttachDisks(attach_req)
print(f"Attached disk {disk_id} to instance {instance_id}")Software-defined networking including VPC creation, subnet management, routing configuration, security groups, and network ACLs.
class VpcClient(AbstractClient):
def __init__(self, credential, region: str, profile = None):
"""
Initialize VPC client for network management.
"""
# VPC Management
def CreateVpc(self, request) -> models.CreateVpcResponse:
"""Create virtual private cloud."""
def DescribeVpcs(self, request) -> models.DescribeVpcsResponse:
"""Query VPC information."""
def ModifyVpcAttribute(self, request) -> models.ModifyVpcAttributeResponse:
"""Modify VPC attributes."""
def DeleteVpc(self, request) -> models.DeleteVpcResponse:
"""Delete VPC."""
# Subnet Management
def CreateSubnet(self, request) -> models.CreateSubnetResponse:
"""Create VPC subnets."""
def DescribeSubnets(self, request) -> models.DescribeSubnetsResponse:
"""Query subnet information."""
def ModifySubnetAttribute(self, request) -> models.ModifySubnetAttributeResponse:
"""Modify subnet attributes."""
def DeleteSubnet(self, request) -> models.DeleteSubnetResponse:
"""Delete subnets."""
# Security Group Management
def CreateSecurityGroup(self, request) -> models.CreateSecurityGroupResponse:
"""Create security groups."""
def DescribeSecurityGroups(self, request) -> models.DescribeSecurityGroupsResponse:
"""Query security group information."""
def AuthorizeSecurityGroupPolicies(self, request) -> models.AuthorizeSecurityGroupPoliciesResponse:
"""Add security group rules."""
def RevokeSecurityGroupPolicies(self, request) -> models.RevokeSecurityGroupPoliciesResponse:
"""Remove security group rules."""Managed MySQL database service with automated backups, monitoring, high availability, and performance optimization.
class CdbClient(AbstractClient):
def __init__(self, credential, region: str, profile = None):
"""Initialize CDB client for MySQL database management."""
# Instance Management
def CreateDBInstance(self, request) -> models.CreateDBInstanceResponse:
"""Create MySQL database instances."""
def DescribeDBInstances(self, request) -> models.DescribeDBInstancesResponse:
"""Query database instance information."""
def RestartDBInstances(self, request) -> models.RestartDBInstancesResponse:
"""Restart database instances."""
def IsolateDBInstance(self, request) -> models.IsolateDBInstanceResponse:
"""Isolate database instance."""
# Database Management
def CreateDatabase(self, request) -> models.CreateDatabaseResponse:
"""Create databases within instance."""
def DescribeDatabases(self, request) -> models.DescribeDatabasesResponse:
"""Query database information."""
def DeleteDatabase(self, request) -> models.DeleteDatabaseResponse:
"""Delete databases."""
# Backup Management
def CreateBackup(self, request) -> models.CreateBackupResponse:
"""Create database backups."""
def DescribeBackups(self, request) -> models.DescribeBackupsResponse:
"""Query backup information."""Real-time and batch speech recognition supporting multiple languages, audio formats, and customization options for various application scenarios.
class AsrClient(AbstractClient):
def __init__(self, credential, region: str, profile = None):
"""Initialize ASR client for speech recognition."""
def SentenceRecognition(self, request) -> models.SentenceRecognitionResponse:
"""Recognize short audio clips (up to 1 minute)."""
def CreateRecTask(self, request) -> models.CreateRecTaskResponse:
"""Create long audio recognition task."""
def DescribeTaskStatus(self, request) -> models.DescribeTaskStatusResponse:
"""Query recognition task status."""S3-compatible object storage with global acceleration, lifecycle management, access control, and integration with other Tencent Cloud services.
class CosClient(AbstractClient):
def __init__(self, credential, region: str, profile = None):
"""Initialize COS client for object storage."""
def PutBucket(self, request) -> models.PutBucketResponse:
"""Create storage buckets."""
def GetService(self, request) -> models.GetServiceResponse:
"""List all buckets."""
def PutObject(self, request) -> models.PutObjectResponse:
"""Upload objects to bucket."""
def GetObject(self, request) -> models.GetObjectResponse:
"""Download objects from bucket."""
def DeleteObject(self, request) -> models.DeleteObjectResponse:
"""Delete objects from bucket."""Multi-Service Integration:
from tencentcloud.common import credential
from tencentcloud.cvm.v20170312 import cvm_client, models as cvm_models
from tencentcloud.cbs.v20170312 import cbs_client, models as cbs_models
from tencentcloud.vpc.v20170312 import vpc_client, models as vpc_models
# Initialize credentials once
cred = credential.DefaultCredentialProvider().get_credential()
# Create multiple service clients
cvm = cvm_client.CvmClient(cred, "ap-shanghai")
cbs = cbs_client.CbsClient(cred, "ap-shanghai")
vpc = vpc_client.VpcClient(cred, "ap-shanghai")
# Create VPC infrastructure
vpc_req = vpc_models.CreateVpcRequest()
vpc_req.VpcName = "MyVPC"
vpc_req.CidrBlock = "10.0.0.0/16"
vpc_response = vpc.CreateVpc(vpc_req)
vpc_id = vpc_response.Vpc.VpcId
# Create subnet
subnet_req = vpc_models.CreateSubnetRequest()
subnet_req.VpcId = vpc_id
subnet_req.SubnetName = "MySubnet"
subnet_req.CidrBlock = "10.0.1.0/24"
subnet_req.Zone = "ap-shanghai-1"
subnet_response = vpc.CreateSubnet(subnet_req)
subnet_id = subnet_response.Subnet.SubnetId
# Launch instance in VPC
run_req = cvm_models.RunInstancesRequest()
run_req.ImageId = "img-9qabwvbn"
run_req.InstanceType = "S5.MEDIUM2"
run_req.VirtualPrivateCloud = cvm_models.VirtualPrivateCloud()
run_req.VirtualPrivateCloud.VpcId = vpc_id
run_req.VirtualPrivateCloud.SubnetId = subnet_id
instance_response = cvm.RunInstances(run_req)
print(f"Created infrastructure: VPC {vpc_id}, Instance {instance_response.InstanceIdSet[0]}")Service Discovery and Dynamic Usage:
import importlib
from tencentcloud.common.common_client import CommonClient
def get_service_client(service_name, version, region="ap-shanghai"):
"""Dynamically create service client."""
try:
# Try specific service client first
module_path = f"tencentcloud.{service_name}.{version}"
client_module = importlib.import_module(f"{module_path}.{service_name}_client")
client_class = getattr(client_module, f"{service_name.capitalize()}Client")
cred = credential.DefaultCredentialProvider().get_credential()
return client_class(cred, region)
except (ImportError, AttributeError):
# Fall back to common client
cred = credential.DefaultCredentialProvider().get_credential()
return CommonClient(service_name, version.replace('v', ''), cred, region)
# Usage
cvm_client = get_service_client("cvm", "v20170312")
cbs_client = get_service_client("cbs", "v20170312")
unknown_client = get_service_client("newservice", "v20230101") # Falls back to CommonClientError Handling Across Services:
from tencentcloud.common.exception.tencent_cloud_sdk_exception import TencentCloudSDKException
def safe_service_call(client, method_name, request):
"""Safely call any service method with error handling."""
try:
method = getattr(client, method_name)
response = method(request)
return response, None
except TencentCloudSDKException as err:
error_info = {
'code': err.get_code(),
'message': err.get_message(),
'request_id': err.get_request_id(),
'service': client.__class__.__name__,
'method': method_name
}
return None, error_info
except AttributeError:
return None, {'error': f'Method {method_name} not found on {client.__class__.__name__}'}
# Usage with any service
response, error = safe_service_call(cvm, "DescribeInstances", cvm_models.DescribeInstancesRequest())
if error:
print(f"API call failed: {error}")
else:
print(f"Success: {response.TotalCount} instances")Install with Tessl CLI
npx tessl i tessl/pypi-tencentcloud-sdk-python