我目前正在尝试使用Python请求向名为CloudSight的图像识别API发送POST请求。我已经使用了一个图像URL,但我很难让它发送一个本地图像文件。到目前为止,我的代码是:
import requests
LOCALE = 'en-US'
LANGUAGE = 'en-US'
URL = 'http://api.cloudsightapi.com/image_responses/'
header = {
'Authorization' : 'CloudSight meSNWQPE7LZ_ybXLMlDflA'
}
imageFile = {'file': ('cigarette.jpg', open('cigarette.jpg', 'rb'), 'image/jpg')}
def postRequest():
print("Here we go again...")
print(imageFile)
postData = {
'image_request[image]': imageFile,
#'image_request[remote_image_url]': 'https://www.google.co.uk/images/branding/googlelogo/2x/googlelogo_color_272x92dp.png',
'image_request[locale]': LOCALE,
'image_request[language]': LANGUAGE
}
rPost = requests.post("https://api.cloudsightapi.com/image_requests", headers=header, data=postData)
print(rPost.status_code)
print(rPost.text)
我知道request通常使用POST请求本身中的参数"files"发送文件:
rPost = requests.post("https://api.cloudsightapi.com/image_requests", headers=header, data=postData, files=imageFile)
然而,我尝试了两种方法,每次都会得到错误:{"error":{"image":["at least one of image or remote_image_url must be set"]}
我也知道这个变量肯定得到了正确的图像,就好像我打印了它给出的变量的内容:{'file': ('cigarette.jpg', <_io.BufferedReader name='cigarette.jpg'>, 'image/jpg')
}据我所知,API要求在参数"image_request[image]"中发送它(根据他们的文档:https://cloudsight.readme.io)如何将图像文件正确发送到CloudSight?
是否尝试调用具有预期名称的文件?
imageFile = {'image_request[image]': ('cigarette.jpg', open('cigarette.jpg', 'rb'), 'image/jpg')}
rPost = requests.post("https://api.cloudsightapi.com/image_requests", headers=header, data=postData, files=imageFile)