
# Python SDK使用指导
本章节介绍了Python SDK的使用说明，您可以参考本章节进行快速集成开发。
 #### 开发前准备
- 已[注册](https://reg.huaweicloud.com/registerui/public/custom/register.html?locale=zh-cn#/register)华为账号并开通华为云，完成[实名认证](https://support.huaweicloud.com/usermanual-account/account_auth_00001.html)。
- 具备已备案的域名用于直播推流和播放，并在视频直播控制台[添加推流和播放域名](https://support.huaweicloud.com/iLive-live/live010002.html)，且已完成[域名关联](https://support.huaweicloud.com/iLive-live/live_01_0026.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)。
 
#### 安装SDK
视频直播服务端SDK支持python3及以上版本。执行" python --version" 检查当前python的版本信息。
使用服务端SDK前，您需要安装"huaweicloudsdkcore "和 "huaweicloudsdklive"，具体的SDK版本号请参见[SDK开发中心](https://console.huaweicloud.com/apiexplorer/#/sdkcenter)。
- 使用pip安装 执行如下命令安装华为云Python SDK核心库以及相关服务库：
  ```
  # 安装核心库
  pip install huaweicloudsdkcore
  # 安装Live服务库
  pip install huaweicloudsdklive
  ```
  

- 使用源码安装
  执行如下命令安装华为云Python SDK核心库以及相关服务库：
  ```
  # 安装核心库
  cd huaweicloudsdkcore-${version}
  python setup.py install
  # 安装Live服务库
  cd huaweicloudsdklive-${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
   # 导入指定Live的库
   from huaweicloudsdklive.v1 import *
   ```
   
   
2. 配置客户端属性。 
   1. 默认配置。
      ```
      # 使用默认配置
      config = HttpConfig.get_default_config()
      ```
      
   
   2. （可选操作）配置代理。
      ```
      # 使用代理服务器（可选）
      # 代理服务器的password直接写入代码，会有很大安全风险。建议密文形式存储在配置文件或者环境变量中，待使用时再解密，以确保安全。
      # 代理配置设置前，请先在本地环境中设置环境变量PROXY_PASSWORD
      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. （可选操作）配置连接。
      ```
      # （可选）配置连接超时，支持统一指定超时时长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，您可以参考[开发前准备]获取。
     ```
     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)。
     ```
     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 = 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) \                 # 日志打印至控制台
       .build()
   ```
   - **endpoint：** 直播服务应用区域和各服务的终端节点，具体请参见[地区和终端节点](https://developer.huaweicloud.com/endpoint?Live)。
   
   - **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 = huaweicloudsdklive.ShowTranscodingsTemplateRequest("play.example.huaweicloud.com")
   response = client.show_transcodings_template(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 = 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. 异步客户端使用。 
   ```
   # 初始化异步客户端，以初始化为例
   live_client = LiveAsyncClient.new_builder(LiveAsyncClient) \
       .with_http_config(config) \
       .with_credentials(credentials) \
       .with_endpoint(endpoint) \
       .build()
   # 发送异步请求
   request = huaweicloudsdklive.ShowTranscodingsTemplateRequest("play.example.huaweicloud.com")
   response = live_client.show_transcodings_template_async(request)
   # 获取异步请求结果
   print(response.result())
   ```
   
   
8. 原始Http侦听器。 
   在某些场景下可能对业务发出的Http请求进行Debug，需要看到原始的Http请求和返回信息，SDK提供侦听器功能获取原始的和加密的Http请求和返回信息。
   ![](https://support.huaweicloud.com/ssdk-live/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)
   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)) \
   ```
   HttpHandler支持"add_request_handler"和"add_response_handler"方法。
   
   
 
#### 代码示例
调用前请根据实际情况替换如下变量：{your endpoint string} 以及 {your project id}。
认证用的AK、SK直接写入代码，会有很大安全风险，建议密文形式存放在配置文件或者环境变量中，待使用时再解密，以确保安全。
本示例以AK、SK保存在环境变量中为例。运行本示例前，请先在本地环境中设置环境变量HUAWEICLOUD_SDK_AK和HUAWEICLOUD_SDK_SK。
```
# 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)
```
