阿里云API调试工具OpenAPI Explore提供OpenAPI文档、API调试和SDK示例,帮助您快速入门API开发。本文介绍如何安装和使用智能媒体管理Python SDK。

前提条件

安装SDK

重要

调用2020-09-30版本的API,需要使用2020-09-30版本的SDK。

使用智能媒体管理Python SDK的操作步骤请参见快速入门

访问凭证

您可以选择以下类型的访问凭证。

  • 临时访问凭证:对于需要高安全性的场景,例如临时授权应用访问IMM,建议使用临时访问凭证。临时访问凭证可以限制访问的有效期,从而减少访问凭证泄露的风险。此外,临时访问凭证支持权限控制,可以有效地避免权限过大的问题。

  • 长期访问凭证:出于安全性考虑,不建议您使用长期访问凭证,建议您使用临时访问凭证。对于需要便利性的场景,长期访问凭证可以在较长时间内免除多次刷新的麻烦。建议每三个月更换一次长期访问凭证,以提高账号的安全性。当长期访问凭证泄露或者不再使用时,应该及时删除或者禁用相关的访问凭证,以免造成安全风险。

使用临时访问凭证

当您准备临时使用Python SDK访问IMM服务时,可以参考配置临时访问凭证

如下以在华东1(杭州)地域中检测图片中的人脸及人脸信息为例,介绍如何使用临时访问凭证通过智能媒体管理Python SDK调用对应API。

  1. 创建demo.py文件并写入如下内容。

    import os
    import sys
    
    from typing import List
    
    from alibabacloud_imm20200930.client import Client as imm20200930Client
    from alibabacloud_tea_openapi import models as open_api_models
    from alibabacloud_imm20200930 import models as imm_20200930_models
    from alibabacloud_tea_util import models as util_models
    from alibabacloud_tea_util.client import Client as UtilClient
    from alibabacloud_sts20150401.client import Client as Sts20150401Client
    from alibabacloud_sts20150401 import models as sts_20150401_models
    
    
    class Sample:
        def __init__(self):
            pass
    
        @staticmethod
        def create_client() -> imm20200930Client:
            """
            使用AK&SK初始化账号Client
            @return: Client
            @throws Exception
            """
            sts_config = open_api_models.Config(
                # 必填,请确保代码运行环境设置了环境变量 ALIBABA_CLOUD_ACCESS_KEY_ID。
                access_key_id=os.environ['ALIBABA_CLOUD_ACCESS_KEY_ID'],
                # 必填,请确保代码运行环境设置了环境变量 ALIBABA_CLOUD_ACCESS_KEY_SECRET。
                access_key_secret=os.environ['ALIBABA_CLOUD_ACCESS_KEY_SECRET']
            )
            # sts Endpoint,需要和imm保持相同地域
            sts_config.endpoint = "sts-share.cn-hangzhou.aliyuncs.com"
            sts_client = Sts20150401Client(sts_config)
            # 调用sts AssumeRole
            assume_role_request = sts_20150401_models.AssumeRoleRequest(
                # sts token有效时间,单位为秒
                duration_seconds=3600,
                # 角色会话名称
                role_session_name="immtest",
                # role arn
                role_arn="acs:ram::xxxxxxx:role/imm-test-role-for-amp"
            )
            runtime = util_models.RuntimeOptions()
            response = sts_client.assume_role_with_options(assume_role_request, runtime)
            credential = response.to_map().get("body", dict()).get("Credentials", dict())
            # 使用sts token创建imm client
            imm_config = open_api_models.Config(
                access_key_id=credential["AccessKeyId"],
                access_key_secret=credential["AccessKeySecret"],
                security_token=credential["SecurityToken"])
            # imm Endpoint 请参考 https://api.aliyun.com/product/imm
            imm_config.endpoint = f'imm.cn-hangzhou.aliyuncs.com'
            return imm20200930Client(imm_config)
    
        @staticmethod
        def main(
            args: List[str],
        ) -> None:
            client = Sample.create_client()
            detect_image_faces_request = imm_20200930_models.DetectImageFacesRequest(
                source_uri='oss://your-bucket-name/your-path/test.jpg',
                project_name='immtest'
            )
            runtime = util_models.RuntimeOptions()
            try:
                # 复制代码运行请自行打印 API 的返回值
                response = client.detect_image_faces_with_options(
                    detect_image_faces_request, runtime)
                print(response.body.to_map())
            except Exception as error:
                # 此处仅做打印展示,请谨慎对待异常处理,在工程项目中切勿直接忽略异常。
                # 错误 message
                print(error.message)
                # 诊断地址
                print(error.data.get("Recommend"))
                UtilClient.assert_as_string(error.message)
    
    
    if __name__ == '__main__':
        Sample.main(sys.argv[1:])
  2. 执行python demo.py命令,控制台输出结果如下。

    {
       "Faces": [
          {
             "Age": 25,
             "AgeSD": 7,
             "Attractive": 0.998,
             "Beard": "none",
             "BeardConfidence": 1,
             "Boundary": {
                "Height": 127,
                "Left": 81,
                "Top": 62,
                "Width": 96
             },
             "Emotion": "happiness",
             "EmotionConfidence": 0.999,
             "FaceQuality": 0.998,
             "FigureClusterId": "figure-cluster-id-unavailable",
             "FigureConfidence": 0.999,
             "FigureId": "30f18b25-db81-4dc6-8461-fd63ab0ef16d",
             "FigureType": "face",
             "Gender": "female",
             "GenderConfidence": 1,
             "Glasses": "none",
             "GlassesConfidence": 1,
             "Hat": "none",
             "HatConfidence": 1,
             "HeadPose": {
                "Pitch": -16.989,
                "Roll": 6.006,
                "Yaw": 7.47
             },
             "Mask": "none",
             "MaskConfidence": 0.83,
             "Mouth": "open",
             "MouthConfidence": 0.998,
             "Sharpness": 1
          }
       ],
       "RequestId": "28084591-0A06-0981-9AD5-B0FBD0967FD7"
    }            

使用长期访问凭证

当您准备在应用或服务中长期使用Go SDK访问IMM服务时,可以参考配置长期访问凭证

如下以使用1.27.3版本的Python SDK在华东2(北京)地域中创建文档转换任务为例,介绍如何使用Python SDK。

  1. 创建demo.py文件并写入如下内容。

    # -*- coding: utf-8 -*-
    # This file is auto-generated, don't edit it. Thanks.
    import os
    import sys
    
    from typing import List
    
    from alibabacloud_imm20200930.client import Client as imm20200930Client
    from alibabacloud_tea_openapi import models as open_api_models
    from alibabacloud_imm20200930 import models as imm_20200930_models
    from alibabacloud_tea_util import models as util_models
    from alibabacloud_tea_util.client import Client as UtilClient
    
    
    class Sample:
        def __init__(self):
            pass
    
        @staticmethod
        def create_client() -> imm20200930Client:
            """
            使用AK&SK初始化账号Client
            @return: Client
            @throws Exception
            """
            # 工程代码泄露可能会导致 AccessKey 泄露,并威胁账号下所有资源的安全性。以下代码示例仅供参考。
            # 建议使用更安全的 STS 方式,更多鉴权访问方式请参见:https://help.aliyun.com/document_detail/378659.html。
            config = open_api_models.Config(
                # 必填,请确保代码运行环境设置了环境变量 ALIBABA_CLOUD_ACCESS_KEY_ID。,
                access_key_id=os.environ['ALIBABA_CLOUD_ACCESS_KEY_ID'],
                # 必填,请确保代码运行环境设置了环境变量 ALIBABA_CLOUD_ACCESS_KEY_SECRET。,
                access_key_secret=os.environ['ALIBABA_CLOUD_ACCESS_KEY_SECRET']
            )
            # Endpoint 请参考 https://api.aliyun.com/product/imm
            config.endpoint = f'imm.cn-beijing.aliyuncs.com'
            return imm20200930Client(config)
    
        @staticmethod
        def main(
            args: List[str],
        ) -> None:
            client = Sample.create_client()
            notification_mns = imm_20200930_models.MNS(
                topic_name='mns_topic_name'
            )
            notification = imm_20200930_models.Notification(
                mns=notification_mns,
                extended_message_uri='oss://your-bucket-name/test-object.json'
            )
            create_office_conversion_task_request = imm_20200930_models.CreateOfficeConversionTaskRequest(
                project_name='immtest',
                source_uri='oss://your-bucket-name/your-path/your-doc.doc',
                target_uri='oss://your-bucket-name/output',
                target_uriprefix='oss://your-bucket-name/output',
                target_type='png',
                notification=notification
            )
            runtime = util_models.RuntimeOptions()
            try:
                # 复制代码运行请自行打印 API 的返回值
                client.create_office_conversion_task_with_options(create_office_conversion_task_request, runtime)
            except Exception as error:
                # 此处仅做打印展示,请谨慎对待异常处理,在工程项目中切勿直接忽略异常。
                # 错误 message
                print(error.message)
                # 诊断地址
                print(error.data.get("Recommend"))
                UtilClient.assert_as_string(error.message)
    
        @staticmethod
        async def main_async(
            args: List[str],
        ) -> None:
            client = Sample.create_client()
            notification_mns = imm_20200930_models.MNS(
                topic_name='mns_topic_name'
            )
            notification = imm_20200930_models.Notification(
                mns=notification_mns,
                extended_message_uri='oss://your-bucket-name/test-object.json'
            )
            create_office_conversion_task_request = imm_20200930_models.CreateOfficeConversionTaskRequest(
                project_name='immtest',
                source_uri='oss://your-bucket-name/your-path/your-doc.doc',
                target_uri='oss://your-bucket-name/output',
                target_uriprefix='oss://your-bucket-name/your-path/your-doc-output',
                target_type='png',
                notification=notification
            )
            runtime = util_models.RuntimeOptions()
            try:
                # 复制代码运行请自行打印 API 的返回值
                await client.create_office_conversion_task_with_options_async(create_office_conversion_task_request, runtime)
            except Exception as error:
                # 此处仅做打印展示,请谨慎对待异常处理,在工程项目中切勿直接忽略异常。
                # 错误 message
                print(error.message)
                # 诊断地址
                print(error.data.get("Recommend"))
                UtilClient.assert_as_string(error.message)
    
    
    if __name__ == '__main__':
        Sample.main(sys.argv[1:])
  2. 执行python demo.py命令,控制台输出结果如下。

    // 文档转换API返回值。
    {
        "TaskId": "OfficeConversion-65ab9c57-4598-4eb4-bf73-****",
        "RequestId": "A637DBBA-3E98-00F5-B0F2-****",
        "EventId": "011-1LNuW4Ws2lRfjGsZl4a****"
    }
    
    // MNS消息,Status为Succeeded表示文档转换任务执行成功。
    {
        "ProjectName": "immtest",
        "DatasetName": "",
        "RequestId": "A637DBBA-3E98-00F5-B0F2-****",
        "StartTime": "2022-07-19T10:41:44.649Z",
        "EndTime": "2022-07-19T10:41:45.26Z",
        "UserData": "",
        "TaskType": "OfficeConversion",
        "TaskId": "OfficeConversion-65ab9c57-4598-4eb4-bf73-****",
        "Status": "Succeeded",
        "Code": "",
        "Message": ""
    }