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

Python SDK User Guide

This section describes how to quickly integrate the Python SDK 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.
    • Plan to use Live in regions in the Chinese mainland.
  • You have obtained and added an ingest domain name and a streaming domain name (both licensed) on the Live console, and associated the domain names.
  • The development environment (Python 3 or later) is available.
  • You have obtained the access key (AK) and secret access key (SK) of the Huawei Cloud account. You can create and view your AK and SK on the My Credentials > Access Keys page of the Huawei Cloud console. For details, see Access Keys.
  • You have obtained the project ID of the corresponding region of Live. You can view the project ID on the My Credentials > API Credentials page of the Huawei Cloud console. For details, see API Credentials.

Installing an SDK

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

Before using the server SDK, you need to install huaweicloudsdkcore and huaweicloudsdklive. For details about SDK versions, 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 Live service library.
    pip install huaweicloudsdklive
    
  • 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 Live service library.
    cd huaweicloudsdklive-${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 Live library.
    from huaweicloudsdklive.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 a proxy.
      1
      2
      3
      4
      5
      6
      7
      8
      # (Optional) Use a proxy server.
      # There will be huge security risks if the password of the proxy server is directly written into the code. You are advised to store the password in ciphertext in the configuration file or environment variables and decrypt the password when using it.
      # Before configuring a proxy, specify the environment variable PROXY_PASSWORD in the local environment.
      config.proxy_protocol = 'http'
      config.proxy_host = 'proxy.huaweicloud.com'
      config.proxy_port = 80
      config.proxy_user = 'username'
      config.proxy_password = os.environ['PROXY_PASSWORD']
      
    3. (Optional) Configure a 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) 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:

    • Permanent AK and SK

      Obtain a permanent AK, SK, and project ID. For details, see Prerequisites.

      1
      credentials = BasicCredentials(ak, sk, project_id)
      
    • Temporary AK and SK

      Obtain a temporary AK, SK, and security token through a token or through an agency.

      1
      credentials = BasicCredentials(ak, sk, project_id).with_security_token(security_token)
      
    The related parameters are as follows:
    • ak: AK of the Huawei Cloud account. You are advised to store the AK in ciphertext in the configuration file or environment variables and decrypt it when using it.
    • sk: SK of the Huawei Cloud account. You are advised to store the SK in ciphertext in the configuration file or environment variables and decrypt it when using it.
    • project_id: ID of the project where Live is provided. Select a project ID based on the region of the project.
    • security_token: security token used for temporary AK and SK authentication

  4. Initialize the client.

    1
    2
    3
    4
    5
    6
    7
    8
    # Initialize the Live client.
    client = LiveAPIClient.new_builder(LiveAPIClient) \
        .with_http_config(config) \
        .with_credentials(credentials) \
        .with_endpoint(endpoint) \
        .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 Live 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 templates as an example.
    request = huaweicloudsdklive.ShowTranscodingsTemplateRequest("play.example.huaweicloud.com")
    response = client.show_transcodings_template(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 = huaweicloudsdklive.ShowTranscodingsTemplateRequest("play.example.huaweicloud.com")
        response = client.show_transcodings_template(request)
    except exception.ServiceResponseException as e:
        print(e.status_code)
        print(e.request_id)
        print(e.error_code)
        print(e.error_msg)
    

  7. Use an asynchronous client.

     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    11
    12
    13
    # Initialize the asynchronous client, as shown in the following example:
    live_client = LiveAsyncClient.new_builder(LiveAsyncClient) \
        .with_http_config(config) \
        .with_credentials(credentials) \
        .with_endpoint(endpoint) \
        .build()
    
    # Send an asynchronous request.
    request = huaweicloudsdklive.ShowTranscodingsTemplateRequest("play.example.huaweicloud.com")
    response = live_client.show_transcodings_template_async(request)
    
    # Obtain the asynchronous response.
    print(response.result())
    

  8. 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)
    
    client = LiveAPIClient.new_builder(LiveAPIClient)\
        .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 the calling, replace the variables {your endpoint string} and {your project id} as needed.

There will be huge security risks if the AK and SK used for authentication are directly written into the code. You are advised to store the AK and SK in ciphertext in the configuration file or environment variables and decrypt them when using them.

In this example, the AK and SK are stored in environment variables. Before running this example, specify the environment variables HUAWEICLOUD_SDK_AK and HUAWEICLOUD_SDK_SK in the local environment.

 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
# coding: utf-8

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

def show_transcodings_template(client):
    try:
        request = huaweicloudsdklive.ShowTranscodingsTemplateRequest("play.example.huaweicloud.com")
        response = client.show_transcodings_template(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["HUAWEICLOUD_SDK_AK"]
    sk = os.environ["HUAWEICLOUD_SDK_SK"]
    endpoint = "{your endpoint}"
    project_id = "{your project id}"

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

    live_client = LiveAPIClient.new_builder(LiveAPIClient) \
        .with_http_config(config) \
        .with_credentials(credentials) \
        .with_endpoint(endpoint) \
        .build()

    show_transcodings_template(live_client)