Common utilities and core components for Tencent Cloud SDK for Python, providing credential management, HTTP clients, authentication, error handling, and foundational classes required by all Tencent Cloud service SDKs
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.
Foundation class that all Tencent Cloud service clients inherit from, providing core functionality for API communication.
class AbstractClient:
def __init__(self, credential, region: str, profile: ClientProfile = None):
"""
Initialize abstract client.
Args:
credential: Credential object for authentication
region (str): Target region for API calls
profile (ClientProfile, optional): Client configuration profile
"""
def call_json(self, action: str, params: dict, headers: dict = None,
options: dict = None) -> dict:
"""
Call API with JSON parameters and return JSON response.
Args:
action (str): API action name (e.g., "DescribeInstances")
params (dict): Request parameters
headers (dict, optional): Custom request headers
options (dict, optional): Request options like {"SkipSign": False, "IsMultipart": False}
Returns:
dict: Parsed JSON response
Raises:
TencentCloudSDKException: On API errors or network issues
"""
def call_sse(self, action: str, params: dict, headers: dict = None,
options: dict = None):
"""
Call API with Server-Sent Events (SSE) response.
Args:
action (str): API action name
params (dict): Request parameters
headers (dict, optional): Custom request headers
options (dict, optional): Request options
Returns:
Generator: SSE event stream
Raises:
TencentCloudSDKException: On API errors or network issues
"""
def call_octet_stream(self, action: str, headers: dict, body: bytes,
options: dict = None) -> dict:
"""
Call API with application/octet-stream content type.
Note: Only works with TC3-HMAC-SHA256 signature method and POST requests.
Args:
action (str): API action name
headers (dict): Request headers
body (bytes): Request body as bytes
options (dict, optional): Request options
Returns:
dict: Parsed JSON response
Raises:
TencentCloudSDKException: On signature method or request method errors
"""
def call(self, action: str, params: dict, options: dict = None,
headers: dict = None) -> str:
"""
Call API and return raw response content.
Args:
action (str): API action name
params (dict): Request parameters
options (dict, optional): Request options
headers (dict, optional): Custom request headers
Returns:
str: Raw response content
Raises:
TencentCloudSDKException: On API errors or network issues
"""
def set_stream_logger(self, stream = None, level: int = None,
log_format: str = None) -> None:
"""
Add a stream handler for logging.
Args:
stream: Output stream (e.g., sys.stdout, sys.stderr)
level (int, optional): Logging level (e.g., logging.DEBUG)
log_format (str, optional): Log message format
"""
def set_file_logger(self, file_path: str, level: int = None,
log_format: str = None) -> None:
"""
Add a file handler for logging.
Args:
file_path (str): Path to log file
level (int, optional): Logging level (e.g., logging.INFO)
log_format (str, optional): Log message format
"""
def set_default_logger(self) -> None:
"""Reset to default (empty) log handler."""General-purpose client that can be used with any Tencent Cloud service without requiring service-specific SDKs.
class CommonClient(AbstractClient):
def __init__(self, service: str, version: str, credential, region: str,
profile: ClientProfile = None):
"""
Create common client for any Tencent Cloud service.
Args:
service (str): Service name (e.g., "cvm", "cos", "vpc")
version (str): API version (e.g., "2017-03-12")
credential: Credential object for authentication
region (str): Target region
profile (ClientProfile, optional): Client configuration
Raises:
TencentCloudSDKException: If required parameters are missing
"""Base class for all API request and response models with serialization support.
class AbstractModel:
@property
def headers(self) -> dict:
"""
Get model headers.
Returns:
dict: Model headers
"""
@headers.setter
def headers(self, headers: dict) -> None:
"""
Set model headers.
Args:
headers (dict): Headers to set
"""
def to_json_string(self, *args, **kwargs) -> str:
"""
Serialize model to JSON string.
Args:
*args: Additional positional arguments for json.dumps
**kwargs: Additional keyword arguments for json.dumps
Returns:
str: JSON string representation
"""
def from_json_string(self, jsonStr: str) -> None:
"""
Deserialize JSON string to populate model.
Args:
jsonStr (str): JSON formatted string
"""from tencentcloud.common.credential import Credential
from tencentcloud.common.common_client import CommonClient
from tencentcloud.common.profile.client_profile import ClientProfile
from tencentcloud.common.profile.http_profile import HttpProfile
# Create credentials
cred = Credential("your-secret-id", "your-secret-key")
# Configure profiles
http_profile = HttpProfile()
http_profile.endpoint = "cvm.tencentcloudapi.com"
client_profile = ClientProfile()
client_profile.httpProfile = http_profile
# Create common client for CVM service
client = CommonClient("cvm", "2017-03-12", cred, "ap-guangzhou", client_profile)
# Call API using JSON
response = client.call_json("DescribeInstances", {
"Limit": 10,
"Offset": 0
})
print("Instances:", response["Response"]["InstanceSet"])
# Call with custom headers
headers = {"X-TC-TraceId": "custom-trace-id"}
response = client.call_json("DescribeRegions", {}, headers=headers)from tencentcloud.common.abstract_client import AbstractClient
from tencentcloud.common.credential import Credential
class CustomServiceClient(AbstractClient):
def __init__(self, credential, region, profile=None):
super().__init__(credential, region, profile)
self._service = "custom-service"
self._apiVersion = "2021-01-01"
# Create custom service client
cred = Credential("your-secret-id", "your-secret-key")
client = CustomServiceClient(cred, "ap-guangzhou")
# Make API calls
response = client.call_json("CustomAction", {"param": "value"})from tencentcloud.common.abstract_model import AbstractModel
import json
class MyModel(AbstractModel):
def __init__(self):
self.field1 = None
self.field2 = None
# Create model
model = MyModel()
model.field1 = "value1"
model.field2 = "value2"
# Serialize to JSON
json_str = model.to_json_string()
print(json_str)
# Deserialize from JSON
new_model = MyModel()
new_model.from_json_string('{"field1": "new_value1", "field2": "new_value2"}')from tencentcloud.common.common_client import CommonClient
# Create client (same as above)
client = CommonClient("service", "version", cred, "region")
# Call SSE endpoint
for event in client.call_sse("StreamingAction", {"param": "value"}):
if "data" in event:
print("Received data:", event["data"])from tencentcloud.common.common_client import CommonClient
# Create client
client = CommonClient("service", "version", cred, "region")
# Upload binary data
with open("file.bin", "rb") as f:
binary_data = f.read()
headers = {"Content-Type": "application/octet-stream"}
response = client.call_octet_stream("UploadBinary", headers, binary_data)import sys
import logging
from tencentcloud.common.common_client import CommonClient
# Create client
client = CommonClient("cvm", "2017-03-12", cred, "ap-guangzhou")
# Add stream logging
client.set_stream_logger(sys.stdout, logging.DEBUG)
# Add file logging
client.set_file_logger("/tmp/sdk.log", logging.INFO)
# API calls will now be logged
response = client.call_json("DescribeInstances", {})from tencentcloud.common.exception.tencent_cloud_sdk_exception import TencentCloudSDKException
from tencentcloud.common.common_client import CommonClient
client = CommonClient("cvm", "2017-03-12", cred, "ap-guangzhou")
try:
response = client.call_json("DescribeInstances", {})
except TencentCloudSDKException as e:
print(f"API Error: {e.get_code()}")
print(f"Message: {e.get_message()}")
print(f"Request ID: {e.get_request_id()}")
except Exception as e:
print(f"Other error: {e}")Install with Tessl CLI
npx tessl i tessl/pypi-tencentcloud-sdk-python-common