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
Digital signature utilities supporting multiple signature methods and comprehensive exception handling for authentication and API errors. Provides secure request signing and robust error management for all Tencent Cloud API interactions.
Cryptographic signing utilities supporting multiple signature algorithms for secure API authentication.
class Sign:
@staticmethod
def sign(secret_key: str, sign_str: str, sign_method: str) -> str:
"""
Generate signature using specified method.
Args:
secret_key (str): Secret key for signing
sign_str (str): String to be signed
sign_method (str): Signature method ("HmacSHA1" or "HmacSHA256")
Returns:
str: Base64-encoded signature
Raises:
TencentCloudSDKException: If signature method is not supported
"""
@staticmethod
def sign_tc3(secret_key: str, date: str, service: str, str2sign: str) -> str:
"""
Generate TC3-HMAC-SHA256 signature.
Args:
secret_key (str): Secret key for signing
date (str): Date in YYYY-MM-DD format
service (str): Service name (e.g., "cvm", "cos")
str2sign (str): String to be signed
Returns:
str: Hexadecimal signature
"""Comprehensive exception class for handling all types of SDK and API errors.
class TencentCloudSDKException(Exception):
def __init__(self, code: str = None, message: str = None,
requestId: str = None):
"""
Create SDK exception.
Args:
code (str, optional): Error code
message (str, optional): Error message
requestId (str, optional): Request ID for tracing
"""
def get_code(self) -> str:
"""
Get error code.
Returns:
str: Error code
"""
def get_message(self) -> str:
"""
Get error message.
Returns:
str: Error message
"""
def get_request_id(self) -> str:
"""
Get request ID.
Returns:
str: Request ID for tracing
"""The following error codes are commonly encountered when using the SDK:
from tencentcloud.common.sign import Sign
# Generate HmacSHA256 signature
secret_key = "your-secret-key"
string_to_sign = "POST\ncvm.tencentcloudapi.com\n/\nAction=DescribeInstances&Nonce=12345"
signature = Sign.sign(secret_key, string_to_sign, "HmacSHA256")
print("Signature:", signature)
# Generate TC3-HMAC-SHA256 signature
date = "2023-01-15"
service = "cvm"
string_to_sign = "TC3-HMAC-SHA256\n1673740800\n2023-01-15/cvm/tc3_request\n..."
signature = Sign.sign_tc3(secret_key, date, service, string_to_sign)
print("TC3 Signature:", signature)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", {})
print("Success:", response)
except TencentCloudSDKException as e:
error_code = e.get_code()
error_message = e.get_message()
request_id = e.get_request_id()
print(f"API Error Code: {error_code}")
print(f"Error Message: {error_message}")
print(f"Request ID: {request_id}")
# Handle specific error types
if error_code == "AuthFailure.SignatureFailure":
print("Check your secret key and signature method")
elif error_code == "RequestLimitExceeded":
print("Rate limited, implementing backoff...")
elif error_code.startswith("ClientNetworkError"):
print("Network issue, check connectivity")
elif error_code.startswith("InvalidCredential"):
print("Credential issue, check secret ID and key")
except Exception as e:
print(f"Unexpected error: {e}")from tencentcloud.common.exception.tencent_cloud_sdk_exception import TencentCloudSDKException
def handle_api_call(api_func, *args, **kwargs):
"""Wrapper function with comprehensive error handling"""
try:
return api_func(*args, **kwargs)
except TencentCloudSDKException as e:
error_code = e.get_code()
# Categorize errors
if error_code.startswith("AuthFailure"):
raise AuthenticationError(f"Authentication failed: {e.get_message()}")
elif error_code.startswith("RequestLimitExceeded"):
raise RateLimitError(f"Rate limited: {e.get_message()}")
elif error_code.startswith("ClientNetworkError"):
raise NetworkError(f"Network error: {e.get_message()}")
else:
raise APIError(f"API error {error_code}: {e.get_message()}")
# Custom exception classes
class AuthenticationError(Exception):
pass
class RateLimitError(Exception):
pass
class NetworkError(Exception):
pass
class APIError(Exception):
pass
# Usage
try:
response = handle_api_call(client.call_json, "DescribeInstances", {})
except AuthenticationError:
print("Fix authentication credentials")
except RateLimitError:
print("Implement retry with backoff")
except NetworkError:
print("Check network connectivity")
except APIError as e:
print(f"API error: {e}")from tencentcloud.common.sign import Sign
from tencentcloud.common.exception.tencent_cloud_sdk_exception import TencentCloudSDKException
def validate_signature_method(method):
"""Validate signature method before use"""
valid_methods = ["HmacSHA1", "HmacSHA256"]
if method not in valid_methods:
raise TencentCloudSDKException(
"InvalidSignatureMethod",
f"Invalid signature method: {method}. Valid methods: {valid_methods}"
)
return method
# Usage
try:
method = validate_signature_method("HmacSHA256")
signature = Sign.sign("secret", "data", method)
except TencentCloudSDKException as e:
print(f"Validation error: {e.get_message()}")from tencentcloud.common.exception.tencent_cloud_sdk_exception import TencentCloudSDKException
import logging
# Setup logging with request ID tracking
logging.basicConfig(
format='%(asctime)s - %(levelname)s - %(message)s',
level=logging.INFO
)
logger = logging.getLogger(__name__)
def make_tracked_api_call(client, action, params):
"""Make API call with request ID tracking"""
try:
response = client.call_json(action, params)
request_id = response.get("Response", {}).get("RequestId")
logger.info(f"API call succeeded - Action: {action}, RequestId: {request_id}")
return response
except TencentCloudSDKException as e:
request_id = e.get_request_id()
logger.error(f"API call failed - Action: {action}, RequestId: {request_id}, Error: {e.get_code()}")
raise
# Usage
try:
response = make_tracked_api_call(client, "DescribeInstances", {"Limit": 10})
except TencentCloudSDKException as e:
print(f"Request {e.get_request_id()} failed: {e.get_message()}")from tencentcloud.common.credential import Credential
from tencentcloud.common.exception.tencent_cloud_sdk_exception import TencentCloudSDKException
def create_validated_credential(secret_id, secret_key, token=None):
"""Create credential with validation"""
try:
return Credential(secret_id, secret_key, token)
except TencentCloudSDKException as e:
if e.get_code() == "InvalidCredential":
print(f"Credential validation failed: {e.get_message()}")
print("Please check:")
print("- Secret ID and key are not empty")
print("- No leading/trailing spaces")
print("- Correct format")
raise
# Usage
try:
cred = create_validated_credential("AKID...", "your-secret-key")
print("Credentials created successfully")
except TencentCloudSDKException as e:
print(f"Failed to create credentials: {e.get_message()}")import os
from tencentcloud.common.credential import DefaultCredentialProvider
def get_secure_credentials():
"""Get credentials using secure methods"""
# Use credential chain for flexibility
provider = DefaultCredentialProvider()
try:
cred = provider.get_credentials()
print("Using credential chain (recommended)")
return cred
except Exception:
print("No credentials found in chain")
# Fallback to environment variables (better than hardcoding)
secret_id = os.getenv("TENCENTCLOUD_SECRET_ID")
secret_key = os.getenv("TENCENTCLOUD_SECRET_KEY")
if secret_id and secret_key:
print("Using environment variables")
return Credential(secret_id, secret_key)
raise TencentCloudSDKException(
"NoCredentialsFound",
"No valid credentials found. Use environment variables or credential files."
)
# Security recommendations:
# 1. Never hardcode credentials in source code
# 2. Use environment variables or credential files
# 3. Use IAM roles when possible (CVM, TKE)
# 4. Rotate credentials regularly
# 5. Use minimum required permissions
# 6. Monitor API usage and errorsInstall with Tessl CLI
npx tessl i tessl/pypi-tencentcloud-sdk-python-common