Updated on 2024-05-09 GMT+08:00

Python SDK

This section describes how to quickly integrate Python SDKs for development.

Prerequisites

  • You have registered with Huawei Cloud and completed real-name authentication.

    If you are a Huawei Cloud (International) user, you need to complete real-name authentication when you:

    • Purchase and use cloud services on Huawei Cloud nodes in the Chinese mainland. In this case, real-name authentication is required by the laws and regulations of the Chinese mainland.
    • Select the Chinese mainland region for MPC.
  • The development environment (Python 3 or later) is available.
  • You have obtained the access key (AK) and secret access key (SK) of the account. You can create and view your AK/SK on the My Credentials > Access Keys page of the console. For details, see Access Keys.
  • You have obtained the project ID of the corresponding region of MPC. You can view the project ID on the My Credentials > API Credentials page of the console. For details, see API Credentials.
  • You have uploaded the media asset files to an OBS bucket in the region of MPC, and authorized MPC to access the OBS bucket. For details, see Uploading Media Files and Authorizing Access to Cloud Resources.

Installing SDK

The MPC SDK supports Python 3 or later. Run the python --version command to check the Python version.

Before using the SDK, you must install huaweicloudsdkcore and huaweicloudsdkmpc. For details about the SDK version, see SDK Center.

  • Using pip

    Run the following commands to install the Python SDK core library and related service libraries:

    1
    2
    3
    4
    # Install the core library.
    pip install huaweicloudsdkcore
    # Install the MPC service library.
    pip install huaweicloudsdkmpc
    
  • Using source code
    Run the following commands to install the Python SDK core library and related service libraries:
    1
    2
    3
    4
    5
    6
    7
    # Install the core library.
    cd huaweicloudsdkcore-${version}
    python setup.py install
    
    # Install the MPC service library.
    cd huaweicloudsdkmpc-${version}
    python setup.py install
    

Procedure

  1. Import the dependent module.

    1
    2
    3
    4
    5
    from huaweicloudsdkcore.auth.credentials import BasicCredentials, GlobalCredentials
    from huaweicloudsdkcore.exceptions import exceptions
    from huaweicloudsdkcore.http.http_config import HttpConfig
    # Import the specified MPC library.
    from huaweicloudsdkmpc.v1 import *
    

  2. Configure client attributes.

    1. Use the default configuration.
      1
      2
      # Use the default configuration.
      config = HttpConfig.get_default_config()
      
    2. (Optional) Configure the proxy.
      1
      2
      3
      4
      5
      6
      7
      8
      user_name = os.environ["USER_NAME"]
      user_password = os.environ["USER_PASSWARD"]
      # (Optional) Use a proxy server.
      config.proxy_protocol = 'http'
      config.proxy_host = 'proxy.huaweicloud.com'
      config.proxy_port = 80
      config.proxy_user = user_name
      config.proxy_password = user_password
      
    3. (Optional) Configure the connection.
      1
      2
      # (Optional) Configure the connection timeout. The timeout can be set to timeout in a unified manner, or set to connect timeout or read timeout as required.
      config.timeout = 3
      
    4. (Optional) Configure SSL.
      1
      2
      3
      4
      # (Optional) Configure whether to skip server certificate verification.
      config.ignore_ssl_verification = True
      # Configure the server CA certificate so that the SDK can verify the server certificate.
      config.ssl_ca_cert = ssl_ca_cert
      

  3. Initialize authentication information.

    You can use one of the following two authentication modes:

    The related parameters are as follows:
    • ak: access key of an account
    • sk: secret access key of an account
    • project_id: ID of the project where MPC is provided. Select a project ID based on the region of the project.
    • security_token: security token used for temporary AK/SK authentication

  4. Initialize the client.

    1
    2
    3
    4
    5
    6
    7
    8
    # Initialize the MPC client.
    client = MpcClient.new_builder(MpcClient) \
        .with_http_config(config) \
        .with_credentials(credentials) \
        .with_endpoint(endpoint) \    # endpoint value, for example, "https://mpc.region01.myhuaweicloud.com"
        .with_file_log(path="test.log", log_level=logging.INFO) \  # Print logs to a file.
        .with_stream_log(log_level=logging.INFO) \                 # Print logs to the console.
        .build()
    
    • endpoint: regions where MPC is used and endpoints of each service. For details, see Regions and Endpoints.
    • with_file_log supports the following configurations:
      • path: log file path
      • log_level: log level. The default value is INFO.
      • max_bytes: size of a log file. The default value is 10485760 bytes.
      • backup_count: number of log files. The default value is 5.
    • with_stream_log supports the following configurations:
      • stream: stream object. The default value is sys.stdout.
      • log_level: log level. The default value is INFO.
    After logging is enabled, access logs are printed for each request in the following format:
    '%(asctime)s %(thread)d %(name)s %(filename)s %(lineno)d %(levelname)s %(message)s'

  5. Send a request and view the response.

    1
    2
    3
    4
    // Initialize the request. The following uses the API for querying transcoding tasks as an example.
    request = ListTranscodingTaskRequest(task_id)
    response = client.list_transcoding_task(request)
    print(response)
    

  6. Perform troubleshooting.

    Table 1 Troubleshooting

    Level 1

    Description

    Level 2

    Description

    ConnectionException

    Connection exception

    HostUnreachableException

    The network is unreachable or access is rejected.

    SslHandShakeException

    SSL authentication is abnormal.

    RequestTimeoutException

    Response timeout exception

    CallTimeoutException

    The server fails to respond to a single request before timeout.

    RetryOutageException

    No valid response is returned after the maximum number of retries specified in the retry policy is reached.

    ServiceResponseException

    Server response exception

    ServerResponseException

    Internal server error. HTTP response code: [500,].

    ClientRequestException

    Invalid request parameter. HTTP response code: [400, 500).

    1
    2
    3
    4
    5
    6
    7
    8
    9
    # Troubleshooting
    try:
        request = request = ListTranscodingTaskRequest(task_id = [1900293])
        response = client.list_transcoding_task(request)
    except exception.ServiceResponseException as e:
        print(e.status_code)
        print(e.request_id)
        print(e.error_code)
        print(e.error_msg)
    

  7. Use the listener to obtain original HTTP requests and responses.

    The original HTTP requests and responses are required for debugging HTTP requests sent by the service side. The SDK provides the listener to obtain the original and encrypted HTTP requests and responses.

    Original information is printed only during debugging. Do not print the header and body of an original HTTP request in the production system because this information contains sensitive data but is not encrypted. If the request body is binary, that is, Content-Type is set to binary, the body will be displayed as *** without the detailed content.

     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    def response_handler(**kwargs):
        logger = kwargs.get("logger")
        response = kwargs.get("response")
        request = response.request
    
        base = "> Request %s %s HTTP/1.1" % (request.method, request.path_url) + "\n"
        if len(request.headers) != 0:
            base = base + "> Headers:" + "\n"
            for each in request.headers:
                base = base + "    %s : %s" % (each, request.headers[each]) + "\n"
        base = base + "> Body: %s" % request.body + "\n\n"
    
        base = base + "< Response HTTP/1.1 %s " % response.status_code + "\n"
        if len(response.headers) != 0:
            base = base + "< Headers:" + "\n"
            for each in response.headers:
                base = base + "    %s : %s" % (each, response.headers[each],) + "\n"
        base = base + "< Body: %s" % response.content
        logger.debug(base)
    
    MpcClient client = MpcClient.new_builder(MpcClient)\
        .with_http_config(config) \
        .with_credentials(credentials) \
        .with_endpoint(endpoint) \
        .with_file_log(path="test.log", log_level=logging.INFO) \
        .with_stream_log(log_level=logging.INFO) \
        .with_http_handler(HttpHandler().add_response_handler(response_handler)) \
    

    The HttpHandler supports the add_request_handler and add_response_handler methods.

Sample Code

Before calling this API, replace SDK_AK, SDK_SK, {your endpoint string}, and {your project id} with the actual ones.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
# coding: utf-8

from huaweicloudsdkcore.auth.credentials import BasicCredentials
from huaweicloudsdkcore.exceptions import exceptions
from huaweicloudsdkcore.http.http_config import HttpConfig
from huaweicloudsdkmpc.v1 import *

def list_transcoding_task(client):
    try:
        request = ListTranscodingTaskRequest(task_id = [1900293])
        response = client.list_transcoding_task(request)
        print(response)
    except exceptions.ClientRequestException as e:
        print(e.status_code)
        print(e.request_id)
        print(e.error_code)
        print(e.error_msg)

if __name__ == "__main__":
    
    ak = os.environ["SDK_AK"]
    sk = os.environ["SDK_SK"]
    project_id = os.environ["{your project id}"]
    endpoint = "{your endpoint}"

    config = HttpConfig.get_default_config()
    config.ignore_ssl_verification = True
    credentials = BasicCredentials(ak, sk, project_id)

    mpc_client = MpcClient.new_builder(MpcClient) \
        .with_http_config(config) \
        .with_credentials(credentials) \
        .with_endpoint(endpoint) \
        .build()
    
list_transcoding_task(mpc_client)