CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/pypi-tencentcloud-sdk-python

Comprehensive Python SDK for integrating with Tencent Cloud services, supporting 240+ cloud services with authentication, error handling, and retry mechanisms.

Overview
Eval results
Files

client-infrastructure.mddocs/

Client Infrastructure

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.

Capabilities

Abstract Client Base Class

Foundation class providing common functionality for all Tencent Cloud service clients including HTTP communication, request signing, authentication, and logging.

class AbstractClient:
    def __init__(self, credential, region: str, profile = None):
        """
        Initialize base client with connection parameters.
        
        Parameters:
        - credential: Credential object for authentication
        - region (str): Tencent Cloud region (e.g., "ap-shanghai", "ap-beijing")
        - profile (ClientProfile, optional): Client configuration profile
        """
    
    def set_stream_logger(self, stream, level):
        """
        Configure logging to output stream.
        
        Parameters:
        - stream: Output stream (e.g., sys.stdout, sys.stderr)
        - level: Logging level (logging.DEBUG, logging.INFO, etc.)
        """
    
    def set_file_logger(self, file_path: str, level):
        """
        Configure rotating file logging.
        
        Parameters:
        - file_path (str): Log file directory path
        - level: Logging level (logging.DEBUG, logging.INFO, etc.)
        
        Note: Creates rotating logs with max 10 files, 512MB each
        """
    
    def set_default_logger(self):
        """
        Remove all log handlers and disable logging output.
        """

Service Client Pattern:

All service clients inherit from AbstractClient and follow this pattern:

from tencentcloud.cvm.v20170312 import cvm_client, models
from tencentcloud.common import credential

# Initialize credentials
cred = credential.Credential("secret_id", "secret_key")

# Create service client
client = cvm_client.CvmClient(cred, "ap-shanghai")

# Optional: Configure logging
import sys
import logging
client.set_stream_logger(sys.stdout, logging.DEBUG)

# Make API calls
request = models.DescribeInstancesRequest()
response = client.DescribeInstances(request)

Generic Common Client

Universal client for accessing any Tencent Cloud service API without importing service-specific modules. Useful for dynamic API access and rapid prototyping.

class CommonClient(AbstractClient):
    def __init__(self, service: str, version: str, credential, region: str, profile = None):
        """
        Initialize generic client for any Tencent Cloud service.
        
        Parameters:
        - service (str): Service name (e.g., "cvm", "cbs", "vpc")
        - version (str): API version (e.g., "2017-03-12")
        - credential: Credential object for authentication
        - region (str): Tencent Cloud region
        - profile (ClientProfile, optional): Client configuration profile
        """
    
    def call_json(self, action: str, params: dict, headers: dict = None):
        """
        Call any service API action with JSON parameters.
        
        Parameters:
        - action (str): API action name (e.g., "DescribeInstances")
        - params (dict): API parameters as dictionary
        - headers (dict, optional): Custom HTTP headers
        
        Returns:
        dict: API response as dictionary
        
        Raises:
        TencentCloudSDKException: If API call fails
        """
    
    def call(self, action: str, params: dict, headers: dict = None):
        """
        Call any service API action (legacy method).
        
        Parameters:
        - action (str): API action name
        - params (dict): API parameters as dictionary  
        - headers (dict, optional): Custom HTTP headers
        
        Returns:
        dict: API response as dictionary
        
        Raises:
        TencentCloudSDKException: If API call fails
        """

Common Client Usage:

from tencentcloud.common.common_client import CommonClient
from tencentcloud.common import credential

# Initialize credentials
cred = credential.Credential("secret_id", "secret_key")

# Create generic client
client = CommonClient("cvm", "2017-03-12", cred, "ap-shanghai")

# Call API with JSON parameters
response = client.call_json("DescribeInstances", {
    "Limit": 10,
    "Filters": [
        {
            "Name": "zone",
            "Values": ["ap-shanghai-1", "ap-shanghai-2"]
        }
    ]
})

print(response["Response"]["InstanceSet"])

Dynamic Service Access:

from tencentcloud.common.common_client import CommonClient
from tencentcloud.common import credential

def call_any_api(service, version, action, params, region="ap-shanghai"):
    """Utility function for dynamic API access."""
    cred = credential.DefaultCredentialProvider().get_credential()
    client = CommonClient(service, version, cred, region)
    return client.call_json(action, params)

# Call different services dynamically
cvm_instances = call_any_api("cvm", "2017-03-12", "DescribeInstances", {"Limit": 5})
cbs_disks = call_any_api("cbs", "2017-03-12", "DescribeDisks", {"Limit": 10})
vpc_list = call_any_api("vpc", "2017-03-12", "DescribeVpcs", {})

Client Configuration Integration

Both AbstractClient and CommonClient support comprehensive configuration through ClientProfile:

from tencentcloud.common.profile.client_profile import ClientProfile
from tencentcloud.common.profile.http_profile import HttpProfile
from tencentcloud.common import retry
from tencentcloud.cvm.v20170312 import cvm_client
from tencentcloud.common import credential
import logging
import sys

# Configure HTTP settings
http_profile = HttpProfile()
http_profile.endpoint = "cvm.ap-shanghai.tencentcloudapi.com"
http_profile.reqMethod = "POST"
http_profile.reqTimeout = 30
http_profile.keepAlive = True

# Configure retry behavior
logger = logging.getLogger("retry")
logger.setLevel(logging.DEBUG)
logger.addHandler(logging.StreamHandler(sys.stderr))

# Configure client profile
client_profile = ClientProfile()
client_profile.httpProfile = http_profile
client_profile.signMethod = "TC3-HMAC-SHA256"
client_profile.language = "en-US"
client_profile.retryer = retry.StandardRetryer(max_attempts=3, logger=logger)

# Create client with configuration
cred = credential.DefaultCredentialProvider().get_credential()
client = cvm_client.CvmClient(cred, "ap-shanghai", client_profile)

Advanced Client Features

Custom Headers:

from tencentcloud.cvm.v20170312 import cvm_client, models

client = cvm_client.CvmClient(cred, "ap-shanghai")
request = models.DescribeInstancesRequest()

# Add custom headers for tracing
request.headers = {
    "X-TC-TraceId": "ffe0c072-8a5d-4e17-8887-a8a60252abca",
    "X-TC-Canary": "true"
}

response = client.DescribeInstances(request)

Region Failover:

from tencentcloud.common.profile.client_profile import ClientProfile, RegionBreakerProfile

# Configure circuit breaker for region failover
region_breaker = RegionBreakerProfile(
    backup_endpoint="ap-beijing.tencentcloudapi.com",
    max_fail_num=3,
    max_fail_percent=0.5,
    window_interval=60,
    timeout=30,
    max_requests=3
)

client_profile = ClientProfile()
client_profile.disable_region_breaker = False
client_profile.region_breaker_profile = region_breaker

client = cvm_client.CvmClient(cred, "ap-shanghai", client_profile)

Proxy Configuration:

from tencentcloud.common.profile.http_profile import HttpProfile

# Configure proxy
http_profile = HttpProfile()
http_profile.proxy = "http://username:password@proxy-server:port"

client_profile = ClientProfile()
client_profile.httpProfile = http_profile

client = cvm_client.CvmClient(cred, "ap-shanghai", client_profile)

Client Lifecycle Management

Single Client Instance:

# Reuse client instance for multiple requests
client = cvm_client.CvmClient(cred, "ap-shanghai")

for zone in ["ap-shanghai-1", "ap-shanghai-2", "ap-shanghai-3"]:
    req = models.DescribeInstancesRequest()
    filter_obj = models.Filter()
    filter_obj.Name = "zone"
    filter_obj.Values = [zone]
    req.Filters = [filter_obj]
    
    resp = client.DescribeInstances(req)
    print(f"Zone {zone}: {resp.TotalCount} instances")

Multi-Region Access:

regions = ["ap-shanghai", "ap-beijing", "ap-guangzhou"]
clients = {}

# Create clients for multiple regions
for region in regions:
    clients[region] = cvm_client.CvmClient(cred, region)

# Use region-specific clients
for region, client in clients.items():
    req = models.DescribeInstancesRequest()
    resp = client.DescribeInstances(req)
    print(f"Region {region}: {resp.TotalCount} instances")

Install with Tessl CLI

npx tessl i tessl/pypi-tencentcloud-sdk-python

docs

authentication.md

client-infrastructure.md

configuration.md

data-models.md

error-handling.md

index.md

service-clients.md

tile.json