### Install from Source Package Source: https://github.com/tencentcloud/tencentcloud-sdk-python/blob/master/README.md Install the SDK by downloading the source code package, extracting it, and running the setup script. ```bash cd tencentcloud-sdk-python python setup.py install ``` -------------------------------- ### Install SDK with Async Support Source: https://github.com/tencentcloud/tencentcloud-sdk-python/blob/master/_autodocs/07-async-support.md Install the SDK with asynchronous support using pip. This includes the necessary httpx library. You can install for all products or a specific one. ```bash pip install 'tencentcloud-sdk-python-common[async]' ``` ```bash pip install 'tencentcloud-sdk-python-cvm[async]' ``` -------------------------------- ### Install All Product SDKs Source: https://github.com/tencentcloud/tencentcloud-sdk-python/blob/master/_autodocs/00-index.md Install the complete SDK package for all Tencent Cloud products. Note that this package is large. ```bash pip install tencentcloud-sdk-python ``` -------------------------------- ### Install using Mirror Source Source: https://github.com/tencentcloud/tencentcloud-sdk-python/blob/master/README.md Use a mirror source to potentially increase download speed when installing SDK packages. ```bash pip install -i https://mirrors.tencent.com/pypi/simple/ --upgrade tencentcloud-sdk-python-cvm ``` -------------------------------- ### Install SDK using pip Source: https://github.com/tencentcloud/tencentcloud-sdk-python/blob/master/README.rst Use pip to install the Tencent Cloud SDK for Python. This is the recommended method for quick setup. ```sh $ pip install tencentcloud-sdk-python ``` -------------------------------- ### Install Specific Product SDK Source: https://github.com/tencentcloud/tencentcloud-sdk-python/blob/master/_autodocs/00-index.md Install the SDK for a particular Tencent Cloud product, such as CVM. ```bash pip install tencentcloud-sdk-python-cvm ``` -------------------------------- ### Install SDK from Source Source: https://github.com/tencentcloud/tencentcloud-sdk-python/blob/master/README.rst Alternatively, clone the SDK's source code from GitHub and install it locally. This method is useful for development or custom builds. ```sh $ git clone https://github.com/tencentcloud/tencentcloud-sdk-python.git $ cd tencentcloud-sdk-python $ python setup.py install ``` -------------------------------- ### Install Common SDK Source: https://github.com/tencentcloud/tencentcloud-sdk-python/blob/master/_autodocs/05-base-client-classes.md Installs the common SDK package. This is an alternative to installing product-specific packages. ```bash # Instead of: pip install tencentcloud-sdk-python-cvm # Use: pip install tencentcloud-sdk-python-common ``` -------------------------------- ### Install Tencent Cloud SDK for Python Source: https://github.com/tencentcloud/tencentcloud-sdk-python/blob/master/_autodocs/README.md Install the SDK using pip. Use the `[async]` extra for asynchronous support. ```bash pip install tencentcloud-sdk-python-common ``` ```bash pip install tencentcloud-sdk-python-common[async] # With async support ``` -------------------------------- ### Install Specific Product SDK Source: https://github.com/tencentcloud/tencentcloud-sdk-python/blob/master/README.md Install the SDK for a specific Tencent Cloud product. Replace '指定产品包名缩写' with the actual product package name abbreviation (e.g., 'cvm'). ```bash pip install --upgrade tencentcloud-sdk-python-指定产品包名缩写 # 如 CVM 产品包:tencentcloud-sdk-python-cvm ``` -------------------------------- ### Install Dependencies Source: https://github.com/tencentcloud/tencentcloud-sdk-python/blob/master/_autodocs/MANIFEST.txt Install the required dependencies for the SDK, such as the 'requests' library, to ensure proper functionality. ```bash pip install requests>=2.16.0 ``` -------------------------------- ### Example Usage Source: https://github.com/tencentcloud/tencentcloud-sdk-python/blob/master/_autodocs/08-http-request.md Demonstrates how to initialize ApiRequest, configure it, create a RequestInternal object, and send a request, including basic error handling. ```APIDOC ## Example ```python from tencentcloud.common.http.request import ApiRequest, RequestInternal # Create request handler api_request = ApiRequest( host="cvm.tencentcloudapi.com", req_timeout=30, is_http=False ) # Enable keep-alive api_request.set_keep_alive(True) # Create request req_inter = RequestInternal( host="cvm.tencentcloudapi.com", method="POST", uri="/", header={ "Host": "cvm.tencentcloudapi.com", "Content-Type": "application/json" }, data='{"Action": "DescribeInstances"}' ) # Send request try: response = api_request.send_request(req_inter) print(f"Status: {response.status_code}") print(f"Body: {response.text}") except Exception as e: print(f"Error: {e}") ``` ``` -------------------------------- ### CVM API Example Source: https://github.com/tencentcloud/tencentcloud-sdk-python/blob/master/_autodocs/05-base-client-classes.md Example demonstrating how to use the CommonClient to call CVM API actions like DescribeInstances and RunInstances. ```APIDOC #### Example: CVM API ```python from tencentcloud.common import credential from tencentcloud.common.common_client import CommonClient cred = credential.Credential( secret_id="your_secret_id", secret_key="your_secret_key" ) client = CommonClient( credential=cred, region="ap-shanghai", service="cvm", version="2017-03-12" ) # DescribeInstances response = client.call_json( action="DescribeInstances", params={"Limit": 5} ) # RunInstances response = client.call_json( action="RunInstances", params={ "ImageId": "img-12345678", "InstanceType": "t3.medium", "ClientToken": "my-token-123" } ) ``` ``` -------------------------------- ### Install Full SDK Package (Sync/Async) Source: https://github.com/tencentcloud/tencentcloud-sdk-python/blob/master/README.md Install the complete SDK package that includes all cloud products. This is not recommended for size-sensitive applications. Use the async version if your Python version is 3.6+ and you need asynchronous functionality. ```bash pip install --upgrade tencentcloud-sdk-python ``` ```bash pip install --upgrade 'tencentcloud-sdk-python[async]' ``` -------------------------------- ### CVM API Example with CommonClient Source: https://github.com/tencentcloud/tencentcloud-sdk-python/blob/master/_autodocs/05-base-client-classes.md Demonstrates creating a CommonClient for the CVM service and calling DescribeInstances and RunInstances actions. ```python from tencentcloud.common import credential from tencentcloud.common.common_client import CommonClient cred = credential.Credential( secret_id="your_secret_id", secret_key="your_secret_key" ) client = CommonClient( credential=cred, region="ap-shanghai", service="cvm", version="2017-03-12" ) # DescribeInstances response = client.call_json( action="DescribeInstances", params={"Limit": 5} ) # RunInstances response = client.call_json( action="RunInstances", params={ "ImageId": "img-12345678", "InstanceType": "t3.medium", "ClientToken": "my-token-123" } ) ``` -------------------------------- ### Install Tencent Cloud SDK Python Common Package Source: https://github.com/tencentcloud/tencentcloud-sdk-python/blob/master/_autodocs/00-index.md Install the core SDK package. Use the `[async]` extra for asynchronous support. ```bash pip install tencentcloud-sdk-python-common ``` ```bash pip install 'tencentcloud-sdk-python-common[async]' ``` -------------------------------- ### Install Common Package (Sync/Async) Source: https://github.com/tencentcloud/tencentcloud-sdk-python/blob/master/README.md Install the common package for the SDK. Use the async version if your Python version is 3.6+ and you need asynchronous functionality. ```bash pip install --upgrade tencentcloud-sdk-python-common ``` ```bash pip install --upgrade 'tencentcloud-sdk-python-common[async]' ``` -------------------------------- ### Instantiate Product-Specific Client (CVM Example) Source: https://github.com/tencentcloud/tencentcloud-sdk-python/blob/master/_autodocs/05-base-client-classes.md Demonstrates indirect usage by instantiating a product-specific client (CVM) which inherits from AbstractClient. This is the recommended way to interact with Tencent Cloud services. ```python from tencentcloud.common import credential from tencentcloud.cvm.v20170312 import cvm_client from tencentcloud.common.profile.client_profile import ClientProfile from tencentcloud.common.profile.http_profile import HttpProfile # Product-specific client inherits from AbstractClient cred = credential.Credential( secret_id="your_secret_id", secret_key="your_secret_key" ) http_profile = HttpProfile() http_profile.endpoint = "cvm.ap-shanghai.tencentcloudapi.com" http_profile.reqTimeout = 30 client_profile = ClientProfile() client_profile.httpProfile = http_profile client = cvm_client.CvmClient(cred, "ap-shanghai", client_profile) # Client automatically uses AbstractClient's infrastructure ``` -------------------------------- ### STS API Example Source: https://github.com/tencentcloud/tencentcloud-sdk-python/blob/master/_autodocs/05-base-client-classes.md Example demonstrating how to use the CommonClient to call STS API actions like AssumeRole to obtain temporary credentials. ```APIDOC #### Example: STS API ```python from tencentcloud.common import credential from tencentcloud.common.common_client import CommonClient cred = credential.Credential( secret_id="your_secret_id", secret_key="your_secret_key" ) client = CommonClient( credential=cred, region="ap-guangzhou", service="sts", version="2018-08-13" ) # AssumeRole response = client.call_json( action="AssumeRole", params={ "RoleArn": "qcs::cam::uin/1234567890:roleName/my-role", "RoleSessionName": "my-session", "DurationSeconds": 3600 } ) credentials = response["Response"]["Credentials"] print(f"TmpSecretId: {credentials['TmpSecretId']}") print(f"TmpSecretKey: {credentials['TmpSecretKey']}") print(f"Token: {credentials['Token']}") ``` ``` -------------------------------- ### Async Client Example for CVM Source: https://github.com/tencentcloud/tencentcloud-sdk-python/blob/master/_autodocs/06-product-client-example.md Demonstrates how to use the asynchronous CVM client to list instances. Requires Python 3.6+ and uses an async context manager for proper resource cleanup. ```python import asyncio from tencentcloud.common import credential from tencentcloud.cvm.v20170312 import cvm_client_async, models async def list_instances(): cred = credential.Credential( secret_id="your_secret_id", secret_key="your_secret_key" ) # Use async context manager for proper cleanup async with cvm_client_async.CvmClient(cred, "ap-shanghai") as client: request = models.DescribeInstancesRequest() request.Limit = 10 response = await client.DescribeInstances(request) print(f"Total: {response.TotalCount}") return response # Run async function result = asyncio.run(list_instances()) ``` -------------------------------- ### STS API Example with CommonClient Source: https://github.com/tencentcloud/tencentcloud-sdk-python/blob/master/_autodocs/05-base-client-classes.md Demonstrates creating a CommonClient for the STS service and calling the AssumeRole action to obtain temporary credentials. ```python from tencentcloud.common import credential from tencentcloud.common.common_client import CommonClient cred = credential.Credential( secret_id="your_secret_id", secret_key="your_secret_key" ) client = CommonClient( credential=cred, region="ap-guangzhou", service="sts", version="2018-08-13" ) # AssumeRole response = client.call_json( action="AssumeRole", params={ "RoleArn": "qcs::cam::uin/1234567890:roleName/my-role", "RoleSessionName": "my-session", "DurationSeconds": 3600 } ) credentials = response["Response"]["Credentials"] print(f"TmpSecretId: {credentials['TmpSecretId']}") print(f"TmpSecretKey: {credentials['TmpSecretKey']}") print(f"Token: {credentials['Token']}") ``` -------------------------------- ### Basic Async Example with CVM Client Source: https://github.com/tencentcloud/tencentcloud-sdk-python/blob/master/_autodocs/07-async-support.md Demonstrates a basic asynchronous call to the CVM API to describe instances. It shows how to create credentials, instantiate an asynchronous client using a context manager, make an API request, and process the response. ```python import asyncio from tencentcloud.common import credential from tencentcloud.cvm.v20170312 import cvm_client_async, models async def main(): # Create credential cred = credential.Credential( secret_id="your_secret_id", secret_key="your_secret_key" ) # Use async context manager for automatic cleanup async with cvm_client_async.CvmClient(cred, "ap-shanghai") as client: # Create request request = models.DescribeInstancesRequest() request.Limit = 10 # Await the async call response = await client.DescribeInstances(request) print(f"Total instances: {response.TotalCount}") for instance in response.InstanceSet: print(f" - {instance.InstanceId}: {instance.InstanceState}") # Run async function asyncio.run(main()) ``` -------------------------------- ### Concurrent Instance Launch with Async Source: https://github.com/tencentcloud/tencentcloud-sdk-python/blob/master/_autodocs/07-async-support.md This example demonstrates launching multiple instances concurrently using asyncio.gather for improved performance in batch operations. It handles potential exceptions during the launch process. ```python import asyncio from tencentcloud.common import credential from tencentcloud.cvm.v20170312 import cvm_client_async, models async def launch_instances_concurrently(): cred = credential.Credential( secret_id="your_secret_id", secret_key="your_secret_key" ) async with cvm_client_async.CvmClient(cred, "ap-shanghai") as client: # Define launch task async def launch_one(index): request = models.RunInstancesRequest() request.ImageId = "img-12345678" request.InstanceType = "t3.medium" request.InstanceName = f"instance-{index}" request.ClientToken = f"token-{index}" response = await client.RunInstances(request) return { "index": index, "instance_ids": response.InstanceIdSet } # Launch 5 instances concurrently tasks = [launch_one(i) for i in range(5)] results = await asyncio.gather(*tasks, return_exceptions=True) for result in results: if isinstance(result, Exception): print(f"Error: {result}") else: print(f"Launched {result['index']}: {result['instance_ids']}") asyncio.run(launch_instances_concurrently()) ``` -------------------------------- ### SDK Version Check Source: https://github.com/tencentcloud/tencentcloud-sdk-python/blob/master/_autodocs/MANIFEST.txt Verify the installed SDK version before using the documentation. Ensure it matches the version specified in the documentation. ```python 3.1.123 ``` -------------------------------- ### Optional vs Required Parameters Source: https://github.com/tencentcloud/tencentcloud-sdk-python/blob/master/_autodocs/12-api-action-reference.md Explains the difference between required and optional parameters and provides an example of setting them. ```APIDOC ## Optional vs Required Parameters - **Required parameters** must be set before calling the API - **Optional parameters** can be omitted (will be None/not sent) - SDK does not validate requirements; server returns error if required param missing ```python request = models.RunInstancesRequest() # Required parameters request.ImageId = "img-12345678" # Required request.InstanceType = "t3.medium" # Required # Optional parameters request.InstanceName = "my-instance" # Optional request.ClientToken = "token-123" # Optional for idempotency request.Quantity = 1 # Optional, defaults server-side ``` ``` -------------------------------- ### Complete ClientProfile Configuration Source: https://github.com/tencentcloud/tencentcloud-sdk-python/blob/master/_autodocs/02-client-configuration.md A comprehensive example demonstrating the configuration of ClientProfile with multiple parameters, including HTTP profile, signing method, language, region breaker, and a custom request client identifier. ```python from tencentcloud.common.profile.client_profile import ClientProfile from tencentcloud.common.profile.http_profile import HttpProfile # Complete configuration http_profile = HttpProfile( protocol="https", endpoint="cvm.ap-beijing.tencentcloudapi.com", reqTimeout=30, keepAlive=True ) client_profile = ClientProfile( signMethod="TC3-HMAC-SHA256", httpProfile=http_profile, language="en-US", disable_region_breaker=False, request_client="my-app-v1.0" ) ``` -------------------------------- ### StopInstances Source: https://github.com/tencentcloud/tencentcloud-sdk-python/blob/master/_autodocs/06-product-client-example.md This example demonstrates how to stop one or more running instances. You can optionally force stop instances without a graceful shutdown or specify a stop mode. ```APIDOC ## StopInstances ### Description Stops running instances. ### Parameters #### Request Parameters - **InstanceIds** (list[str]) - Required - Instance IDs to stop - **ForceStop** (bool) - Optional - Force stop without graceful shutdown (default False) - **StopType** (str) - Optional - Stop mode: "SOFT_FIRST" or "HARD" ### Request Example ```python from tencentcloud.common import credential from tencentcloud.cvm.v20170312 import cvm_client, models cred = credential.Credential( secret_id="your_secret_id", secret_key="your_secret_key" ) client = cvm_client.CvmClient(cred, "ap-shanghai") # Stop instances request = models.StopInstancesRequest() request.InstanceIds = ["i-abc123", "i-def456"] request.ForceStop = False try: response = client.StopInstances(request) print(f"Operation request ID: {response.RequestId}") except Exception as e: print(f"Error: {e}") ``` ``` -------------------------------- ### With Custom Headers Source: https://github.com/tencentcloud/tencentcloud-sdk-python/blob/master/_autodocs/06-product-client-example.md This example shows how to include custom headers, such as trace IDs, in your requests for better request tracking and management. ```APIDOC ## With Custom Headers ### Description Include custom headers like trace IDs for request tracking. ### Request Example ```python from tencentcloud.common import credential from tencentcloud.cvm.v20170312 import cvm_client, models cred = credential.Credential( secret_id="your_secret_id", secret_key="your_secret_key" ) client = cvm_client.CvmClient(cred, "ap-shanghai") # Create request with custom headers request = models.DescribeInstancesRequest() request.Limit = 10 # Set custom headers request.headers = { "X-TC-TraceId": "custom-trace-123", "X-TC-Canary": "1" } try: response = client.DescribeInstances(request) print(f"Total: {response.TotalCount}") except Exception as e: print(f"Error: {e}") ``` ``` -------------------------------- ### Configure Multiple Endpoints for Region Failover Source: https://github.com/tencentcloud/tencentcloud-sdk-python/blob/master/_autodocs/10-region-failover.md This example shows how to configure a client with both a primary and a backup endpoint for region failover. It specifies the primary region in the client constructor and provides the backup endpoint within the `RegionBreakerProfile`. ```python # Primary region (from constructor) client = cvm_client.CvmClient(cred, "ap-shanghai") # Primary: ap-shanghai # With custom HTTP endpoint for primary http_profile = HttpProfile() http_profile.endpoint = "cvm.ap-shanghai.tencentcloudapi.com" profile = ClientProfile( httpProfile=http_profile, disable_region_breaker=False, region_breaker_profile=RegionBreakerProfile( backup_endpoint="ap-guangzhou.tencentcloudapi.com" # Backup ) ) ``` -------------------------------- ### Get Credentials from Configuration File Source: https://github.com/tencentcloud/tencentcloud-sdk-python/blob/master/README.md Load credentials from a local configuration file. The SDK supports default paths for Windows, Linux, and macOS. ```python from tencentcloud.common import credential cred = credential.ProfileCredential().get_credential() ``` -------------------------------- ### Configure and Use Region Failover Source: https://github.com/tencentcloud/tencentcloud-sdk-python/blob/master/_autodocs/10-region-failover.md This example demonstrates how to set up region failover by configuring `RegionBreakerProfile` with backup endpoints and failover parameters, then enabling it in `ClientProfile` for a CVM client. The SDK will automatically attempt to use the backup endpoint if the primary fails. ```python from tencentcloud.common import credential from tencentcloud.common.profile.client_profile import ClientProfile, RegionBreakerProfile from tencentcloud.cvm.v20170312 import cvm_client, models from tencentcloud.common.exception import TencentCloudSDKException # Create credential cred = credential.Credential( secret_id="your_secret_id", secret_key="your_secret_key" ) # Configure region breaker breaker_profile = RegionBreakerProfile( backup_endpoint="ap-guangzhou.tencentcloudapi.com", max_fail_num=3, max_fail_percent=0.5, window_interval=60, timeout=30, max_requests=3 ) # Enable region failover client_profile = ClientProfile( disable_region_breaker=False, region_breaker_profile=breaker_profile ) # Create client client = cvm_client.CvmClient(cred, "ap-shanghai", client_profile) # Request with automatic failover try: request = models.DescribeInstancesRequest() request.Limit = 10 response = client.DescribeInstances(request) # If primary (ap-shanghai) fails, automatically uses backup (ap-guangzhou) print(f"Total instances: {response.TotalCount}") except TencentCloudSDKException as e: print(f"Error: {e.get_code()}: {e.get_message()}") if e.get_request_id(): print(f"Request ID: {e.get_request_id()}") ``` -------------------------------- ### Configure HTTP Options Source: https://github.com/tencentcloud/tencentcloud-sdk-python/blob/master/_autodocs/06-product-client-example.md Customize HTTP-level options like endpoint, request timeout, method, and keep-alive. This example also sets the client language for responses. ```python from tencentcloud.common import credential from tencentcloud.common.profile.http_profile import HttpProfile from tencentcloud.common.profile.client_profile import ClientProfile from tencentcloud.cvm.v20170312 import cvm_client, models # Configure HTTP http_profile = HttpProfile() http_profile.endpoint = "cvm.ap-shanghai.tencentcloudapi.com" http_profile.reqTimeout = 30 http_profile.reqMethod = "POST" http_profile.keepAlive = True # Configure client client_profile = ClientProfile() client_profile.httpProfile = http_profile client_profile.language = "en-US" # English responses cred = credential.Credential( secret_id="your_secret_id", secret_key="your_secret_key" ) client = cvm_client.CvmClient(cred, "ap-shanghai", client_profile) request = models.DescribeInstancesRequest() request.Limit = 10 response = client.DescribeInstances(request) print(response.to_json_string(indent=2)) ``` -------------------------------- ### Asynchronous API Call Example Source: https://github.com/tencentcloud/tencentcloud-sdk-python/blob/master/README.md Demonstrates how to perform asynchronous API calls using the CVM client. Ensure you use the `*_client_async` module and `async with` for proper resource management. API calls require an `await` prefix. ```python import asyncio import os from tencentcloud.common import credential from tencentcloud.common.exception.tencent_cloud_sdk_exception import TencentCloudSDKException from tencentcloud.cvm.v20170312 import cvm_client_async, models async def main(): try: cred = credential.Credential( os.environ.get("TENCENTCLOUD_SECRET_ID"), os.environ.get("TENCENTCLOUD_SECRET_KEY")) # 使用异步客户端,支持 async context manager async with cvm_client_async.CvmClient(cred, "ap-shanghai") as client: req = models.DescribeInstancesRequest() resp = await client.DescribeInstances(req) print(resp.to_json_string()) except TencentCloudSDKException as err: print(err) # 运行异步函数 asyncio.get_event_loop().run_until_complete(main()) ``` -------------------------------- ### Test Region Failover with CVM Client Source: https://github.com/tencentcloud/tencentcloud-sdk-python/blob/master/_autodocs/10-region-failover.md This example demonstrates how to initialize a CVM client with a configured `RegionBreakerProfile` and simulate requests to test failover behavior. It includes error handling to catch exceptions during API calls. ```python from tencentcloud.common import credential from tencentcloud.common.profile.client_profile import ClientProfile, RegionBreakerProfile from tencentcloud.cvm.v20170312 import cvm_client, models cred = credential.Credential( secret_id="your_secret_id", secret_key="your_secret_key" ) breaker = RegionBreakerProfile( backup_endpoint="ap-beijing.tencentcloudapi.com" ) profile = ClientProfile( disable_region_breaker=False, region_breaker_profile=breaker ) client = cvm_client.CvmClient(cred, "ap-shanghai", profile) # Make requests to test failover behavior for i in range(20): try: request = models.DescribeInstancesRequest() response = client.DescribeInstances(request) print(f"Request {i}: Success") except Exception as e: print(f"Request {i}: Failed - {e}") if i == 10: print("Simulating failure scenario...") ``` -------------------------------- ### Enable Request Logging for Debugging with Tencent Cloud SDK for Python Source: https://github.com/tencentcloud/tencentcloud-sdk-python/blob/master/_autodocs/11-common-use-cases.md Configures detailed logging for SDK requests and responses to aid in debugging. This example sets up a stream handler to output logs to standard output. ```python import logging import sys from tencentcloud.common import credential from tencentcloud.cvm.v20170312 import cvm_client, models # Set up logging handler = logging.StreamHandler(sys.stdout) handler.setLevel(logging.DEBUG) formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s') handler.setFormatter(formatter) logger = logging.getLogger('tencentcloud_sdk_common') logger.setLevel(logging.DEBUG) logger.addHandler(handler) cred = credential.Credential("your_secret_id", "your_secret_key") client = cvm_client.CvmClient(cred, "ap-shanghai") # Can also enable client-level logging # client.set_stream_logger(stream=sys.stdout, level=logging.DEBUG) request = models.DescribeInstancesRequest() request.Limit = 5 response = client.DescribeInstances(request) print(f"Response: {response.TotalCount}") ``` -------------------------------- ### Initialize ClientProfile Source: https://github.com/tencentcloud/tencentcloud-sdk-python/blob/master/_autodocs/02-client-configuration.md Instantiate ClientProfile with default settings. This is the most basic configuration. ```python from tencentcloud.common.profile.client_profile import ClientProfile # Basic configuration client_profile = ClientProfile() ``` -------------------------------- ### Create a Product Client Source: https://github.com/tencentcloud/tencentcloud-sdk-python/blob/master/_autodocs/00-index.md Standard pattern for creating a client for any Tencent Cloud product. Replace `PRODUCT` and `VERSION` with the specific service shortname and API version. ```python from tencentcloud.common import credential from tencentcloud.PRODUCT.VVERSION import PRODUCT_client, models # Create credential cred = credential.Credential(secret_id, secret_key) # Create client client = PRODUCT_client.ProductClient(cred, region, profile) # Create request request = models.ApiActionRequest() # Call API response = client.ApiAction(request) ``` -------------------------------- ### Get Formatted Error String from Exception Source: https://github.com/tencentcloud/tencentcloud-sdk-python/blob/master/_autodocs/04-exceptions.md Use the `str()` function on a `TencentCloudSDKException` object to get a formatted string representation of the error, including its code, message, and request ID. This is useful for logging or displaying detailed error information to the user. ```python try: # ... API call that fails ... except TencentCloudSDKException as e: # String representation print(str(e)) # Output: [TencentCloudSDKException] code:RequestLimitExceeded message:rate limit exceeded requestId:abc-123-def ``` -------------------------------- ### Request Parameter Types Source: https://github.com/tencentcloud/tencentcloud-sdk-python/blob/master/_autodocs/12-api-action-reference.md Lists the supported data types for request parameters and provides examples. ```APIDOC ## Request Parameter Types | Type | Python | Example | |------|--------|---------| | String | str | `"ap-shanghai"` | | Integer | int | `10` | | Boolean | bool | `True` | | Array | list | `["item1", "item2"]` | | Object | ModelClass | `Filter()` with properties set | | Timestamp | int | `1609459200` (Unix seconds) | ``` -------------------------------- ### Creating a Request Model Instance Source: https://github.com/tencentcloud/tencentcloud-sdk-python/blob/master/_autodocs/12-api-action-reference.md Demonstrates how to instantiate a request model and set simple and complex parameters. Ensure the correct models are imported from the respective service package. ```python from tencentcloud.cvm.v20170312 import models # Create request instance request = models.DescribeInstancesRequest() # Set simple parameters request.Limit = 20 request.Offset = 0 # Set complex parameters (nested objects) filter_obj = models.Filter() filter_obj.Name = "zone" filter_obj.Values = ["ap-shanghai-1"] request.Filters = [filter_obj] ``` -------------------------------- ### Get Credentials from Environment Variables Source: https://github.com/tencentcloud/tencentcloud-sdk-python/blob/master/README.md Retrieve Tencent Cloud SecretId and SecretKey from environment variables TENCENTCLOUD_SECRET_ID and TENCENTCLOUD_SECRET_KEY. ```python from tencentcloud.common import credential cred = credential.EnvironmentVariableCredential().get_credential() ``` -------------------------------- ### RunInstances Source: https://github.com/tencentcloud/tencentcloud-sdk-python/blob/master/_autodocs/06-product-client-example.md Launches new CVM instances with specified configurations. ```APIDOC ## RunInstances ### Description Launches new CVM instances. ### Method POST (implied by SDK usage) ### Endpoint Not explicitly defined, SDK method call. ### Parameters #### Request Parameters (Selected) - **ImageId** (str) - Yes - Image ID (OS image) - **InstanceType** (str) - Yes - Instance type (e.g., "t3.medium") - **InstanceChargeType** (str) - No - Billing type: "PREPAID" or "POSTPAID_BY_HOUR" - **SystemDisk** (SystemDisk) - No - System disk configuration - **DataDisks** (list[DataDisk]) - No - Data disks to attach - **VirtualPrivateCloud** (VirtualPrivateCloud) - No - VPC network configuration - **SecurityGroupIds** (list[str]) - No - Security group IDs - **InstanceName** (str) - No - Display name for instance - **ClientToken** (str) - No - Idempotency key ### Request Example ```python from tencentcloud.common import credential from tencentcloud.cvm.v20170312 import cvm_client, models cred = credential.Credential( secret_id="your_secret_id", secret_key="your_secret_key" ) client = cvm_client.CvmClient(cred, "ap-shanghai") # Create request request = models.RunInstancesRequest() request.ImageId = "img-12345678" # Image ID request.InstanceType = "t3.medium" # Instance type request.InstanceChargeType = "POSTPAID_BY_HOUR" request.InstanceName = "my-instance" request.ClientToken = "my-unique-token-123" # For idempotency # Configure system disk request.SystemDisk = models.SystemDisk() request.SystemDisk.DiskSize = 50 request.SystemDisk.DiskType = "CLOUD_PREMIUM" # Configure network request.VirtualPrivateCloud = models.VirtualPrivateCloud() request.VirtualPrivateCloud.VpcId = "vpc-abc123" request.VirtualPrivateCloud.SubnetId = "subnet-def456" # Configure security group request.SecurityGroupIds = ["sg-xyz789"] # Launch instance try: response = client.RunInstances(request) print(f"Instances created: {response.InstanceIdSet}") except Exception as e: print(f"Error: {e}") ``` ### Response #### Success Response (200) - **InstanceIdSet** (list[str]) - Set of instance IDs created. ``` -------------------------------- ### ClientProfile Class Initialization Source: https://github.com/tencentcloud/tencentcloud-sdk-python/blob/master/_autodocs/02-client-configuration.md Demonstrates how to initialize the ClientProfile class with various configuration options for SDK requests. ```APIDOC ## ClientProfile Class Controls SDK-level request behavior including signing method, language, retry policy, and region failover. #### Signature ```python class ClientProfile(object): def __init__( self, signMethod: str = None, httpProfile: HttpProfile = None, language: str = "zh-CN", disable_region_breaker: bool = True, region_breaker_profile: 'RegionBreakerProfile' = None, request_client: str = None, retryer: 'StandardRetryer' = None ) -> None ``` #### Parameters | Parameter | Type | Required | Default | Description | |-----------|------|----------|---------|-------------| | signMethod | str | No | "TC3-HMAC-SHA256" | Signature algorithm: "TC3-HMAC-SHA256", "HmacSHA1", "HmacSHA256" | | httpProfile | HttpProfile | No | None | HTTP configuration; uses default if not provided | | language | str | No | "zh-CN" | Response language: "zh-CN" (Chinese) or "en-US" (English) | | disable_region_breaker | bool | No | True | Disable region failover circuit breaker | | region_breaker_profile | RegionBreakerProfile | No | None | Custom region breaker configuration | | request_client | str | No | None | Custom request client identifier (max 128 chars, alphanumeric + -_,;.) | | retryer | StandardRetryer | No | None | Custom retry policy | #### Properties | Property | Type | Description | |----------|------|-------------| | httpProfile | HttpProfile | HTTP profile configuration | | signMethod | str | Signature algorithm method | | language | str | Response language | | disable_region_breaker | bool | Region breaker flag | | region_breaker_profile | RegionBreakerProfile | Region breaker configuration | | request_client | str | Custom request client identifier | | retryer | StandardRetryer | Retry policy | | unsignedPayload | bool | Skip request body signing (defaults to False) | #### Validation - `language` must be "zh-CN" or "en-US"; raises `TencentCloudSDKException` otherwise - `request_client` must match pattern `^[0-9a-zA-Z-_,;.]+$`; warns and truncates to 128 chars if invalid - If `disable_region_breaker` is False, creates default `RegionBreakerProfile` if not provided #### Example ```python from tencentcloud.common.profile.client_profile import ClientProfile from tencentcloud.common.profile.http_profile import HttpProfile from tencentcloud.common.retry import StandardRetryer import logging # Basic configuration client_profile = ClientProfile() # Custom signing and language client_profile = ClientProfile( signMethod="TC3-HMAC-SHA256", language="en-US" ) # With HTTP profile http_profile = HttpProfile( endpoint="cvm.ap-shanghai.tencentcloudapi.com", reqTimeout=30 ) client_profile = ClientProfile( httpProfile=http_profile ) # With retry policy logger = logging.getLogger("tencentcloud") retryer = StandardRetryer(max_attempts=3, logger=logger) client_profile = ClientProfile( retryer=retryer ) # With region breaker client_profile = ClientProfile( disable_region_breaker=False ) # Complete configuration http_profile = HttpProfile( protocol="https", endpoint="cvm.ap-beijing.tencentcloudapi.com", reqTimeout=30, keepAlive=True ) client_profile = ClientProfile( signMethod="TC3-HMAC-SHA256", httpProfile=http_profile, language="en-US", disable_region_breaker=False, request_client="my-app-v1.0" ) ``` ``` -------------------------------- ### Query Instance List (Detailed) Source: https://github.com/tencentcloud/tencentcloud-sdk-python/blob/master/README.md This detailed version allows for advanced configuration, including HTTP profiles, client profiles, retry mechanisms, and custom headers. It's recommended to manage credentials via environment variables. ```python # -*- coding: utf-8 -*- import os import sys import logging from tencentcloud.common import credential, retry from tencentcloud.common.exception.tencent_cloud_sdk_exception import TencentCloudSDKException # 导入对应产品模块的client models。 from tencentcloud.cvm.v20170312 import cvm_client, models # 导入可选配置类 from tencentcloud.common.profile.client_profile import ClientProfile from tencentcloud.common.profile.http_profile import HttpProfile try: # 实例化一个认证对象,入参需要传入腾讯云账户secretId,secretKey。 # 为了保护密钥安全,建议将密钥设置在环境变量中或者配置文件中,请参考本文凭证管理章节。 # 硬编码密钥到代码中有可能随代码泄露而暴露,有安全隐患,并不推荐。 # cred = credential.Credential("secretId", "secretKey") cred = credential.Credential( os.environ.get("TENCENTCLOUD_SECRET_ID"), os.environ.get("TENCENTCLOUD_SECRET_KEY")) # 实例化一个http选项,可选的,没有特殊需求可以跳过。 http_profile = HttpProfile() # 如果需要指定proxy访问接口,可以按照如下方式初始化hp # http_profile = HttpProfile(proxy="http://用户名:密码@代理IP:代理端口") http_profile.scheme = "https" # 在外网互通的网络环境下支持http协议(默认是https协议),建议使用https协议 http_profile.keepAlive = True # 状态保持,默认是False http_profile.reqMethod = "GET" # get请求(默认为post请求) http_profile.reqTimeout = 30 # 请求超时时间,单位为秒(默认60秒) http_profile.endpoint = "cvm.ap-shanghai.tencentcloudapi.com" # 指定接入地域域名(默认就近接入) # 实例化一个client选项,可选的,没有特殊需求可以跳过。 client_profile = ClientProfile() client_profile.signMethod = "TC3-HMAC-SHA256" # 指定签名算法 client_profile.language = "en-US" # 指定展示英文(默认为中文) client_profile.httpProfile = http_profile # 当发生网络/限频错误时, 重试3次, 并通过logger打印日志 logger = logging.getLogger("retry") logger.setLevel(logging.DEBUG) logger.addHandler(logging.StreamHandler(sys.stderr)) client_profile.retryer = retry.StandardRetryer(max_attempts=3, logger=logger) # 实例化要请求产品(以cvm为例)的client对象,clientProfile是可选的。 client = cvm_client.CvmClient(cred, "ap-shanghai", client_profile) # 打印日志按照如下方式,也可以设置log_format,默认为 '%(asctime)s %(process)d %(filename)s L%(lineno)s %(levelname)s %(message)s' # client.set_stream_logger(stream=sys.stdout, level=logging.DEBUG) # client.set_file_logger(file_path="/log", level=logging.DEBUG) 日志文件滚动输出,最多10个文件,单个文件最大512MB # client.set_default_logger() 去除所有log handler,默认不输出 # 实例化一个cvm实例信息查询请求对象,每个接口都会对应一个request对象。 req = models.DescribeInstancesRequest() # 填充请求参数,这里request对象的成员变量即对应接口的入参。 # 您可以通过官网接口文档或跳转到request对象的定义处查看请求参数的定义。 resp_filter = models.Filter() # 创建Filter对象, 以zone的维度来查询cvm实例。 resp_filter.Name = "zone" resp_filter.Values = ["ap-shanghai-1", "ap-shanghai-2"] req.Filters = [resp_filter] # Filters 是成员为Filter对象的列表 # python sdk支持自定义header如 X-TC-TraceId、X-TC-Canary,可以按照如下方式指定,header必须是字典类型的 headers = { "X-TC-TraceId": "ffe0c072-8a5d-4e17-8887-a8a60252abca" } req.headers = headers # 通过client对象调用DescribeInstances方法发起请求。注意请求方法名与请求对象是对应的,headers为可选参数。 # 返回的resp是一个DescribeInstancesResponse类的实例,与请求对象对应。 resp = client.DescribeInstances(req) # 输出json格式的字符串回包 print(resp.to_json_string(indent=2)) # 也可以取出单个值。 # 您可以通过官网接口文档或跳转到response对象的定义处查看返回字段的定义。 print(resp.TotalCount) except TencentCloudSDKException as err: print(err) ``` -------------------------------- ### Pattern 5: Query/Get Operations Source: https://github.com/tencentcloud/tencentcloud-sdk-python/blob/master/_autodocs/12-api-action-reference.md Get detailed information about a single resource. This pattern is useful for retrieving specific details about a particular resource. ```APIDOC ## DescribeImage ### Description Retrieves detailed information about a specific image. ### Method client.DescribeImage ### Parameters #### Request Body - **ImageId** (str) - Required - The ID of the image to describe. ### Response #### Success Response (200) - **ImageName** (str) - The name of the image. - **ImageSize** (int) - The size of the image in GB. ### Request Example ```python request = models.DescribeImageRequest() request.ImageId = "img-12345678" response = client.DescribeImage(request) print(f"Name: {response.ImageName}") print(f"Size: {response.ImageSize}") ``` ### Response Example ```json { "ImageName": "Ubuntu Server 20.04 LTS", "ImageSize": 50 } ``` ``` -------------------------------- ### Launch CVM Instances with RunInstances Source: https://github.com/tencentcloud/tencentcloud-sdk-python/blob/master/_autodocs/06-product-client-example.md Use this snippet to launch new CVM instances. Ensure you have valid credentials and specify required parameters like ImageId and InstanceType. Configure optional settings for disks, network, and security groups as needed. ```python from tencentcloud.common import credential from tencentcloud.cvm.v20170312 import cvm_client, models cred = credential.Credential( secret_id="your_secret_id", secret_key="your_secret_key" ) client = cvm_client.CvmClient(cred, "ap-shanghai") # Create request request = models.RunInstancesRequest() request.ImageId = "img-12345678" # Image ID request.InstanceType = "t3.medium" # Instance type request.InstanceChargeType = "POSTPAID_BY_HOUR" request.InstanceName = "my-instance" request.ClientToken = "my-unique-token-123" # For idempotency # Configure system disk request.SystemDisk = models.SystemDisk() request.SystemDisk.DiskSize = 50 request.SystemDisk.DiskType = "CLOUD_PREMIUM" # Configure network request.VirtualPrivateCloud = models.VirtualPrivateCloud() request.VirtualPrivateCloud.VpcId = "vpc-abc123" request.VirtualPrivateCloud.SubnetId = "subnet-def456" # Configure security group request.SecurityGroupIds = ["sg-xyz789"] # Launch instance try: response = client.RunInstances(request) print(f"Instances created: {response.InstanceIdSet}") except Exception as e: print(f"Error: {e}") ``` -------------------------------- ### Initialize and Use ApiRequest Source: https://github.com/tencentcloud/tencentcloud-sdk-python/blob/master/_autodocs/08-http-request.md Demonstrates how to create an ApiRequest instance, configure it for keep-alive, construct a RequestInternal object, and send the request. Includes basic error handling for network issues. ```python from tencentcloud.common.http.request import ApiRequest, RequestInternal # Create request handler api_request = ApiRequest( host="cvm.tencentcloudapi.com", req_timeout=30, is_http=False ) # Enable keep-alive api_request.set_keep_alive(True) # Create request req_inter = RequestInternal( host="cvm.tencentcloudapi.com", method="POST", uri="/", header={ "Host": "cvm.tencentcloudapi.com", "Content-Type": "application/json" }, data='{"Action": "DescribeInstances"}' ) # Send request try: response = api_request.send_request(req_inter) print(f"Status: {response.status_code}") print(f"Body: {response.text}") except Exception as e: print(f"Error: {e}") ``` -------------------------------- ### Basic CVM Instance Retrieval Source: https://github.com/tencentcloud/tencentcloud-sdk-python/blob/master/_autodocs/00-index.md Demonstrates the fundamental steps to create a credential, initialize a CVM client for a specific region, and make a request to describe instances. The `TotalCount` from the response is printed. ```python from tencentcloud.common import credential from tencentcloud.cvm.v20170312 import cvm_client, models # Create credential cred = credential.Credential( secret_id="your_secret_id", secret_key="your_secret_key" ) # Create client client = cvm_client.CvmClient(cred, "ap-shanghai") # Make request request = models.DescribeInstancesRequest() response = client.DescribeInstances(request) print(response.TotalCount) ``` -------------------------------- ### Get Credentials from Instance Role Source: https://github.com/tencentcloud/tencentcloud-sdk-python/blob/master/README.md Automatically fetch temporary credentials from instance metadata when running on a Tencent Cloud CVM instance with an assigned role. ```python from tencentcloud.common import credential cred = credential.CVMRoleCredential().get_credential() ``` -------------------------------- ### Handle Rate Limit Error Source: https://github.com/tencentcloud/tencentcloud-sdk-python/blob/master/_autodocs/04-exceptions.md Detect and handle `RequestLimitExceeded` errors by pausing and retrying requests. The example demonstrates checking the error code within the exception. ```python from tencentcloud.common import credential from tencentcloud.cvm.v20170312 import cvm_client, models from tencentcloud.common.exception import TencentCloudSDKException cred = credential.Credential( secret_id="your_secret_id", secret_key="your_secret_key" ) client = cvm_client.CvmClient(cred, "ap-shanghai") try: # Making many requests rapidly for i in range(100): req = models.DescribeInstancesRequest() resp = client.DescribeInstances(req) except TencentCloudSDKException as e: if "RequestLimitExceeded" in e.get_code(): print(f"Rate limited: {e.get_message()}") print(f"Please wait before retrying") else: raise ``` -------------------------------- ### Create/Run Operation Pattern Source: https://github.com/tencentcloud/tencentcloud-sdk-python/blob/master/_autodocs/12-api-action-reference.md Create new resources with specified configuration. This pattern involves setting detailed parameters for basic configuration, networking, storage, and other options. `ClientToken` can be used for idempotency. ```python request = models.RunInstancesRequest() # Basic configuration request.ImageId = "img-12345678" request.InstanceType = "t3.medium" request.Quantity = 1 # Network configuration request.VirtualPrivateCloud = models.VirtualPrivateCloud() request.VirtualPrivateCloud.VpcId = "vpc-abc123" request.VirtualPrivateCloud.SubnetId = "subnet-def456" # Storage configuration request.SystemDisk = models.SystemDisk() request.SystemDisk.DiskType = "CLOUD_PREMIUM" request.SystemDisk.DiskSize = 50 # Other options request.InstanceName = "my-instance" request.ClientToken = "unique-token-123" # For idempotency response = client.RunInstances(request) print(f"Created instances: {response.InstanceIdSet}") ``` -------------------------------- ### Handle Authorization Errors (4xx) Source: https://github.com/tencentcloud/tencentcloud-sdk-python/blob/master/_autodocs/12-api-action-reference.md Detect and manage authorization issues by checking for 'UnauthorizedOperation' in the exception code. This helps in guiding users to correct their IAM policies. ```python try: response = client.RunInstances(request) except TencentCloudSDKException as e: if "UnauthorizedOperation" in e.get_code(): print(f"Not authorized: {e.get_message()}") print("Check IAM policies") ``` -------------------------------- ### Generic API Calls with CommonClient Source: https://github.com/tencentcloud/tencentcloud-sdk-python/blob/master/_autodocs/00-index.md Use `CommonClient` to make API calls without installing product-specific SDK packages. Specify the service, version, and parameters directly. ```python from tencentcloud.common.common_client import CommonClient # No need to install product-specific package client = CommonClient( credential=cred, region="ap-shanghai", service="cvm", version="2017-03-12" ) # Call any action response = client.call_json( action="DescribeInstances", params={"Limit": 10} ) ```