TencentCloud Python SDK

repository·master·Indexed 20 days ago

https://github.com/tencentcloud/tencentcloud-sdk-python

A development toolkit for the Cloud API 3.0 platform that allows developers to interact with TencentCloud services programmatically. It supports Python 2.7 and all Python 3.x versions, offering both synchronous and asynchronous calling modes (available from version 3.1.0). The SDK provides flexible installation options via pip (full or product-specific packages), multiple credential management methods including environment variables and instance roles, and advanced features like region breaker for disaster recovery.

Tokens
4.5K
Snippets
9
Records
21
Agent score
72%

What's inside tencentcloud-sdk-python

  1. Manage credentials for Tencent Cloud SDK

    master

    The Python SDK supports several methods for managing secretId and secretKey credentials:

    1. Environment Variables

    Reads TENCENTCLOUD_SECRET_ID and TENCENTCLOUD_SECRET_KEY from your environment.

    2. Configuration Files

    Uses an .ini formatted file at the following locations:

    • Windows: c:\Users\NAME\.tencentcloud\credentials
    • Linux: ~/.tencentcloud/credentials or /etc/tencentcloud/credentials

    File Format:

    [default]
    secret_id = xxxxx
    secret_key = xxxxx

    3. Role Assumption (STS)

    Used to obtain temporary credentials by assuming a pre-created role in the Tencent Cloud console.

    4. Instance Role (CVM)

    Automatically fetches and refreshes temporary credentials from the instance metadata service when a role is bound to the instance.

    5. Credential Provider Chain

    The SDK provides a default chain that attempts to retrieve credentials in this order: Environment Variables -> Configuration Files -> Instance Role -> TKE OIDC Credentials.

    from tencentcloud.common import credential
    
    # 1. Environment Variables
    cred = credential.EnvironmentVariableCredential().get_credential()
    
    # 2. Configuration Files
    cred = credential.ProfileCredential().get_credential()
    
    # 3. Role Assumption (STS)
    cred = credential.STSAssumeRoleCredential("SecretId", "SecretKey", "RoleArn", "RoleSessionName")
    
    # 4. Instance Role (CVM)
    cred = credential.CVMRoleCredential().get_credential()
    
    # 5. Default Provider Chain
    cred = credential.DefaultCredentialProvider().get_credential()
    
    # 6. TKE OIDC Credentials
    cred = credential.DefaultTkeOIDCRoleArnProvider().get_credential()
  2. Use the TencentCloud Python SDK (Asynchronous)

    master

    Asynchronous support is available from version 3.1.0 and requires the httpx library.

    Requirements:

    • Install the async common package: pip install 'tencentcloud-sdk-python-common[async]'.
    • Use the *_client_async module (e.g., cvm_client_async) instead of the synchronous client.
    • Use async with to ensure the client is correctly released.
    • All API interfaces are identical to the synchronous version, but you must await the calls.

    Note: The asynchronous SDK is designed for high-concurrency scenarios.

    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"))
    
            # Use the async client with an 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())
  3. Configure Proxy for TencentCloud SDK

    master

    If your environment requires a proxy to access the internet, you can configure it in two ways:

    1. Via HttpProfile: Specify the proxy parameter when initializing an HttpProfile object.
    2. Via Environment Variables: Set the https_proxy system environment variable.

    Failure to configure a proxy in a restricted environment may result in connection timeout exceptions.

  4. Install the TencentCloud Python SDK via Pip

    master

    You can install the SDK using pip. There are two main approaches: installing the full SDK or installing specific product SDKs.

    Important Notes:

    • You must choose either the full SDK or specific product SDKs, not both.
    • If installing multiple product packages, ensure they and the common package are kept at the same version.
    • For Python 3 environments, use pip3.
    • If you require asynchronous functionality (available for Python >= 3.6), you must install the [async] version of the common package.

    Installation Options:

    1. Specific Product SDK (Recommended for size efficiency): First, install the required common package, then the specific product package (e.g., cvm).

    2. Full Product SDK: Installs all cloud product calling code. This is larger in size.

    Using Mirror Sources: If the official source is slow, use the Tencent mirror: pip install -i https://mirrors.tencent.com/pypi/simple/ --upgrade <package_name>

    # 1. Install specific product SDK (Recommended)
    # Install common package (sync version)
    pip install --upgrade tencentcloud-sdk-python-common
    # OR install common package (async version for Python >= 3.6)
    pip install --upgrade 'tencentcloud-sdk-python-common[async]'
    
    # Install specific product (e.g., CVM)
    pip install --upgrade tencentcloud-sdk-python-cvm
    
    # 2. Install Full Product SDK
    pip install --upgrade tencentcloud-sdk-python
    # OR for async support
    pip install --upgrade 'tencentcloud-sdk-python[async]'
  5. Troubleshoot urllib3 and OpenSSL ImportError

    master

    If you encounter the error: ImportError: urllib3 v2.0 only supports OpenSSL 1.1.1+, currently the 'ssl' module is compiled with 'OpenSSL 1.0.x'

    This is caused by requests version 2.30.0+ adapting to urllib3 2.0. To resolve this, use one of the following methods:

    1. Downgrade urllib3: Force a version in the 1.26.x range (the SDK supports urllib3>=1.21.1,<3).
    2. Upgrade OpenSSL: Recompile your Python environment using OpenSSL 1.1.1 or higher.
  6. Breaking Changes in TencentCloud ADP (Agent Development Platform) v2026-05-20

    master

    The latest release for the TencentCloud Agent Development Platform (adp) includes significant breaking changes. Several timer-related interfaces and data structures have been removed. If your application relies on TimerTask management, you must migrate to the updated AppTrigger interfaces.

    Removed Interfaces:

    • CreateTimerTask
    • DeleteTimerTask
    • DescribeTimerTask
    • DescribeTimerTaskRunLogList
    • DescribeTimerTaskSummaryList
    • MarkAppTriggerRunLogRead
    • MarkTimerTaskRunLogRead
    • ModifyTimerTask
    • PauseTimerTask
    • ResumeTimerTask
    • RunTimerTaskNow

    Removed Data Structures:

    • TimerConfig
    • TimerProfile
    • TimerStatus
    • TimerTask
    • TimerTaskSummary

    Updated Interfaces (Now require Scope and UserId): Most AppTrigger related methods (e.g., CreateAppTrigger, DeleteAppTrigger, DescribeAppTrigger, ModifyAppTrigger, PauseAppTrigger, ResumeAppTrigger, RunAppTriggerNow) now require Scope and UserId as input parameters.

  7. Resolve SSL certificate verification errors on macOS

    master

    When using Python 3.6+ on macOS, you may encounter [SSL: CERTIFICATE_VERIFY_FAILED] errors because Python does not use the system default certificates.

    To fix this, run the following command in your terminal (adjust the path based on your Python version):

    sudo "/Applications/Python 3.6/Install Certificates.command"

    Alternatively, you can manually configure the httpProfile in the SDK to specify a custom certificate path or disable verification entirely.

    # Specify a custom certificate
    httpProfile.certification = "/path/to/certification"
    
    # Skip certificate verification
    httpProfile.certification = False
  8. Use the TencentCloud Python SDK (Synchronous)

    master

    To make synchronous API calls, follow these steps:

    1. Obtain SecretID and SecretKey from the TencentCloud Console.
    2. Initialize a credential.Credential object.
    3. Initialize a product-specific client (e.g., cvm_client.CvmClient) with the credentials and a target region.
    4. Create a request object (e.g., models.DescribeInstancesRequest).
    5. Call the client method with the request object.

    For advanced usage, you can customize the HttpProfile (proxy, timeout, scheme) and ClientProfile (signature method, language, retryer).

    import os
    from tencentcloud.common import credential
    from tencentcloud.common.exception.tencent_cloud_sdk_exception import TencentCloudSDKException
    from tencentcloud.cvm.v20170312 import cvm_client, models
    
    try:
        # Use environment variables for security
        cred = credential.Credential(
            os.environ.get("TENCENTCLOUD_SECRET_ID"),
            os.environ.get("TENCENTCLOUD_SECRET_KEY"))
        
        # Initialize client with credentials and region
        client = cvm_client.CvmClient(cred, "ap-shanghai")
    
        # Create request object
        req = models.DescribeInstancesRequest()
        
        # Execute request
        resp = client.DescribeInstances(req)
    
        print(resp.to_json_string())
    except TencentCloudSDKException as err:
        print(err)