全部产品
云市场

Python SDK

更新时间:2019-04-11 14:50:44

准备工作

  1. 在安装和使用阿里云SDK前,确保您已经注册阿里云账号并生成访问访问密钥(AccessKey)。详情参考创建AccessKey
  2. 安装Python SDK核心库。
    • 使用依赖包工具安装(推荐)。
      执行以下命令,安装阿里云SDK核心库:
      1. pip install aliyun-python-sdk-core
    • 自行下载安装。
      您可以使用git clone或其它手段下载aliyun-python-sdk-core并自行添加解决方案。aliyun-python-sdk-core GitHub地址:aliyun-python-sdk-core
  3. 安装图像搜索Python SDK。
    • 使用依赖包工具安装(推荐)。
      执行以下命令,安装图像搜索Python SDK:
      1. pip install aliyun-python-sdk-imagesearch
    • 自行下载安装。
      您可以使用git clone或其它手段下载aliyun-python-sdk-imagesearch并自行添加解决方案。aliyun-python-sdk-imagesearch GitHub地址:aliyun-python-sdk-imagesearch

完整代码示例

  1. # -*- coding: utf8 -*-
  2. from aliyunsdkcore.client import AcsClient
  3. import base64
  4. import aliyunsdkimagesearch.request.v20190325.AddImageRequest as AddImageRequest
  5. import aliyunsdkimagesearch.request.v20190325.DeleteImageRequest as DeleteImageRequest
  6. import aliyunsdkimagesearch.request.v20190325.SearchImageRequest as SearchImageRequest
  7. # 创建 AcsClient 实例
  8. client = AcsClient("<your-access-key-id>", "<your-access-key-secret>", "<region>")
  9. # 添加图片
  10. request = AddImageRequest.AddImageRequest()
  11. request.set_endpoint("imagesearch.<region>.aliyuncs.com")
  12. request.set_InstanceName("demo")
  13. request.set_ProductId("test")
  14. request.set_PicName("test")
  15. with open('/home/admin/demo.jpg', 'rb') as imgfile:
  16. encoded_pic_content = base64.b64encode(imgfile.read())
  17. request.set_PicContent(encoded_pic_content)
  18. response = client.do_action_with_exception(request)
  19. print(response)
  20. # 搜索图片
  21. request = SearchImageRequest.SearchImageRequest()
  22. request.set_endpoint("imagesearch.<region>.aliyuncs.com")
  23. request.set_InstanceName("demo")
  24. with open('/home/admin/demo.jpg', 'rb') as imgfile:
  25. encoded_pic_content = base64.b64encode(imgfile.read())
  26. request.set_PicContent(encoded_pic_content)
  27. response = client.do_action_with_exception(request)
  28. print(response)
  29. # 删除图片
  30. request = DeleteImageRequest.DeleteImageRequest()
  31. request.set_endpoint("imagesearch.<region>.aliyuncs.com")
  32. request.set_InstanceName("demo")
  33. request.set_ProductId("test")
  34. response = client.do_action_with_exception(request)
  35. print(response)