
# Python SDK
本章节介绍了Python SDK的使用说明，您可以参考本章节进行快速集成开发。
 #### 开发前准备
- 已[注册](https://reg.huaweicloud.com/registerui/public/custom/register.html#/register)华为账号并开通华为云，已进行[实名认证](https://support.huaweicloud.com/usermanual-account/account_auth_00001.html)。
- 已具备开发环境 ，支持python 3及以上版本。
- 已获取账号对应的Access Key（AK）和Secret Access Key（SK）。请在控制台"我的凭证 \> 访问密钥"页面上创建和查看您的AK/SK。具体请参见[访问密钥](https://support.huaweicloud.com/usermanual-ca/ca_01_0003.html)。
- 已获取转码服务对应区域的项目ID，请在控制台"我的凭证 \> API凭证"页面上查看项目ID。具体请参见[API凭证](https://support.huaweicloud.com/usermanual-ca/ca_01_0002.html)。
- 已将需要处理的媒资文件上传至MPC同区域的OBS桶中，并将OBS桶进行授权，允许MPC访问。具体请参见[上传音视频文件](https://support.huaweicloud.com/usermanual-mpc/mpc010002.html)和[获取云资源授权](https://support.huaweicloud.com/usermanual-mpc/mpc010003.html)。
 
#### 安装SDK
媒体转码服务端SDK支持python 3及以上版本。执行" python --version"检查当前python的版本信息。
使用服务端SDK前，您需要安装"huaweicloudsdkcore "和"huaweicloudsdkmpc"，具体的SDK版本号请参见[SDK开发中心](https://sdkcenter.developer.huaweicloud.com/)。
- 使用pip安装 执行如下命令安装Python SDK核心库以及相关服务库：
  ```
  # 安装核心库
  pip install huaweicloudsdkcore
  # 安装MPC服务库
  pip install huaweicloudsdkmpc
  ```
  

- 使用源码安装
  执行如下命令安装Python SDK核心库以及相关服务库：
  ```
  # 安装核心库
  cd huaweicloudsdkcore-${version}
  python setup.py install
  # 安装MPC服务库
  cd huaweicloudsdkmpc-${version}
  python setup.py install
  ```
  
 
#### 开始使用
1. 导入依赖模块。 
   ```
   from huaweicloudsdkcore.auth.credentials import BasicCredentials, GlobalCredentials
   from huaweicloudsdkcore.exceptions import exceptions
   from huaweicloudsdkcore.http.http_config import HttpConfig
   # 导入指定MPC的库
   from huaweicloudsdkmpc.v1 import *
   ```
   
   
2. 配置客户端属性。 
   1. 默认配置。
      ```
      # 使用默认配置
      config = HttpConfig.get_default_config()
      ```
      
   
   2. 代理配置（可选）。
      ```
      user_name = os.environ["USER_NAME"]
      user_password = os.environ["USER_PASSWORD"]
      # 使用代理服务器（可选）
      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. 连接配置（可选）。
      ```
      # 配置连接超时（可选），支持统一指定超时时长timeout=timeout，或分别指定超时时长timeout=(connect timeout, read timeout)
      config.timeout = 3
      ```
      
   
   4. SSL配置（可选）。
      ```
      # 配置跳过服务端证书验证（可选）
      config.ignore_ssl_verification = True
      # 配置服务器端CA证书，用于SDK验证服务端证书合法性
      config.ssl_ca_cert = ssl_ca_cert
      ```
      
   
   
   
   
3. 初始化认证信息。 
   支持两种方式认证，您可以根据实际情况进行选择。
   - 使用永久AK/SK 首先需要获取永久AK和SK，以及projectId，您可以参考[开发前准备]获取。
     ```
     ak = os.environ["SDK_AK"]
     sk = os.environ["SDK_SK"]
     project_id = os.environ["PROJECT_ID"]
     credentials = BasicCredentials(ak, sk, project_id)
     ```
     
   
   - 使用临时AK/SK 首先需要获得临时AK、SK和SecurityToken，您可以[通过token获取](https://support.huaweicloud.com/api-iam/iam_04_0002.html)或者[通过委托授权获取](https://support.huaweicloud.com/api-iam/iam_04_0101.html)。
     ```
     ak = os.environ["SDK_AK"]
     sk = os.environ["SDK_SK"]
     project_id = os.environ["PROJECT_ID"]
     security_token = os.environ["SECURITY_TOKEN"]
     credentials = BasicCredentials(ak, sk, project_id).with_security_token(security_token)
     ```
     
   
   
   相关参数说明如下所示：
   - **ak**：账号Access Key。
   
   - **sk**：账号Secret Access Key 。
   
   - **project_id**：云服务所在项目ID ，根据您需要操作的项目所属区域选择对应的项目ID。
   
   - **security_token**：采用临时AK/SK认证场景下的安全票据。
    
   
   
4. 初始化客户端。 
   ```
   # 初始化转码服务的客户端
   client = MpcClient.new_builder(MpcClient) \
       .with_http_config(config) \
       .with_credentials(credentials) \
       .with_endpoint(endpoint) \    # endpoint值如 "https://mpc.region01.myhuaweicloud.com"
       .with_file_log(path="test.log", log_level=logging.INFO) \  # 日志打印至文件
       .with_stream_log(log_level=logging.INFO) \                 # 日志打印至控制台
       .build()
   ```
   - **endpoint** ：MPC应用区域和各服务的终端节点，具体请参见[地区和终端节点](https://developer.huaweicloud.com/endpoint?MPC)。
   
   - **with_file_log** 支持如下配置：
     - path：日志文件路径。
     
     - log_level：日志级别，默认INFO。
     
     - max_bytes：单个日志文件大小，默认为10485760 bytes。
     
     - backup_count：日志文件个数，默认为5个。
      
   
   - **with_stream_log** 支持如下配置：
     - stream：流对象，默认sys.stdout。
     
     - log_level：日志级别，默认INFO。
      
   
   
   打开日志开关后，每次请求将打印访问日志，格式如下：
   ```
   '%(asctime)s %(thread)d %(name)s %(filename)s %(lineno)d %(levelname)s %(message)s'
   ```
   
   
5. 发送请求并查看响应。 
   ```
   // 初始化请求，以调用查询转码任务接口为例
   request = ListTranscodingTaskRequest(task_id)
   response = client.list_transcoding_task(request)
   print(response)
   ```
   
   
6. 异常处理。 
   表1异常处理 
   | 一级分类                     | 一级分类说明  | 二级分类                     | 二级分类说明                      |
   |:---|:---|:---|:---|
   | ConnectionException      | 连接类异常   | HostUnreachableException | 网络不可达、被拒绝                   |
   | ConnectionException      | 连接类异常   | SslHandShakeException    | SSL认证异常                     |
   | RequestTimeoutException  | 响应超时异常  | CallTimeoutException     | 单次请求，服务器处理超时未返回             |
   | RequestTimeoutException  | 响应超时异常  | RetryOutageException     | 在重试策略消耗完成以后，仍无有效的响应         |
   | ServiceResponseException | 服务器响应异常 | ServerResponseException  | 服务端内部错误，Http响应码：\[500,\]    |
   | ServiceResponseException | 服务器响应异常 | ClientRequestException   | 请求参数不合法，Http响应码：\[400， 500) |
      
   ```
   # 异常处理
   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. 原始Http侦听器。 
   在某些场景下可能对业务发出的Http请求进行Debug，需要看到原始的Http请求和返回信息，SDK提供侦听器功能获取原始的和加密的Http请求和返回信息。
   ![](https://support.huaweicloud.com/sdkreference-mpc/public_sys-resources/caution_3.0-zh-cn.png)
   原始信息打印仅在debug阶段使用，请不要在生产系统中将原始的Http头和Body信息打印到日志，这些信息并未加密且其中包含敏感数据；当Body体为二进制内容，即Content-Type标识为二进制时 body为"\*\*\*"，详细内容不输出。
   ```
   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)) \
   ```
   HttpHandler支持"add_request_handler"和"add_response_handler"方法。
   
   
 
#### 代码示例
调用前请根据实际情况替换如下变量："SDK_AK"、"SDK_SK"、{your endpoint string} 以及 {your project id}。
```
# 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)
```
