AI开发平台MODELARTS-通过APP认证的方式访问在线服务:方式三:使用Python语言通过AppCode认证鉴权方式发送预测请求

时间:2024-09-03 11:41:22

方式三:使用Python语言通过AppCode认证鉴权方式发送预测请求

  1. 下载Python SDK并在开发工具中完成SDK配置。具体操作请参见在Python环境中集成API请求签名的SDK
  2. 创建请求体,进行预测请求。
    • 输入为文件格式
      # coding=utf-8
      
      import requests
      import os
      
      if __name__ == '__main__':
          # Config url, app code and file path.
          url = "在线服务的调用地址"
          # 认证用的app_code硬编码到代码中或者明文存储都有很大的安全风险,建议在配置文件或者环境变量中密文存放,使用时解密,确保安全;
          # 本示例以app_code保存在环境变量中来实现身份验证为例,运行本示例前请先在本地环境中设置环境变量HUAWEICLOUD_APP_CODE。
          app_code = os.environ["HUAWEICLOUD_APP_CODE"]
          file_path = "预测文件的本地路径"
      
          # Send request.
          headers = {
              'X-Apig-AppCode': app_code
          }
          files = {
              'images': open(file_path, 'rb')
          }
          resp = requests.post(url, headers=headers, files=files)
      
          # Print result
          print(resp.status_code)
          print(resp.text)

      “files”中的参数名由在线服务的输入参数决定,需要和“类型”为“file”的输入参数“名称”保持一致。此处以“images”为例。

    • 输入为文本格式(json类型)

      读取本地预测文件并进行base64编码的请求体示例如下:

      # coding=utf-8
      
      import base64
      import requests
      import os
      
      if __name__ == '__main__':
          # Config url, app code and request body.
          url = "在线服务的调用地址"
          # 认证用的app_code硬编码到代码中或者明文存储都有很大的安全风险,建议在配置文件或者环境变量中密文存放,使用时解密,确保安全;
          # 本示例以app_code保存在环境变量中来实现身份验证为例,运行本示例前请先在本地环境中设置环境变量HUAWEICLOUD_APP_CODE。
          app_code = os.environ["HUAWEICLOUD_APP_CODE"]
          file_path = "预测文件的本地路径"
          with open(file_path, "rb") as file:
              base64_data = base64.b64encode(file.read()).decode("utf-8")
      
          # Send request
          headers = {
              'Content-Type': 'application/json',
              'X-Apig-AppCode': app_code
          }
          body = {
              'image': base64_data
          }
          resp = requests.post(url, headers=headers, json=body)
      
          # Print result
          print(resp.status_code)
          print(resp.text)

      “body”中的参数名由在线服务的输入参数决定,需要和“类型”“string”的输入参数“名称”保持一致。此处以“image”为例。“body”中的base64_data值为string类型。

support.huaweicloud.com/usermanual-standard-modelarts/inference-modelarts-0025.html