python使用requests接口调用modelarts推理服务,输入数据为单个图片


输入的数据是一个图片,demo里面图片的名称为test.jpg,test.jpg保存在和推理脚本同目录下

Appcode方式认证(推荐)

获取Appcode方式如下

https://bbs.huaweicloud.com/blogs/250513

推理代码如下

import requests

input_img_path='./test.jpg'
files = {'images': open(input_img_path, 'rb')}
#print(input_data)
infer_header={'X-Apig-AppCode': '<YOUR-APP-CODE>'}
#print(infer_header)
infer_url = 'https://xxxxxxxxxx.apig.cn-north-4.huaweicloudapis.com/v1/infers/<YOUR-OWN-INFER-URL>'
r = requests.post(infer_url, files=files,verify=False,headers=infer_header)
print(r.text)

<YOUR-APP-CODE>替换为 https://bbs.huaweicloud.com/blogs/250513 第4步生成的appcode

infer_url替换为 https://bbs.huaweicloud.com/blogs/250513 第六步复制的url


token方式认证

token认证方式需要获得aksk认证方式的rest接口


iam_token.json文件准备参见,注意事项也参考

https://bbs.huaweicloud.com/blogs/233074

注意:代码一共分两部分,第一部分是获取token,第二部分是调用推理请求。获取token的代码每12个小时更新一次就可以,不能频繁的调用,如果每次推理请求都调用一次token的更新,会导致获取token请求被拒绝。

#Get token
import requests
IAM_URL='https://iam.cn-north-4.myhuaweicloud.com/v3/auth/tokens'
token_headers = {'Content-Type': 'application/json;charset=utf8'}
iam_token_file='./iam_token.json'
token_data = open(iam_token_file, 'rb').read()
r = requests.post(IAM_URL, data=token_data,verify=False,headers=token_headers)
token_value = r.headers['X-Subject-Token']
#print(token_value)

#call service api
input_img_path='./test.jpg'
files = {'images': open(input_img_path, 'rb')}
#print(input_data)
infer_header={'X-Auth-Token': token_value}
#print(infer_header)
infer_url = 'https://xxxxxxxxx.apig.cn-north-4.huaweicloudapis.com/v1/infers/xxxxxxxxxxxxx'
r = requests.post(infer_url, files=files,verify=False,headers=infer_header)
print(r.text)


(完)