我目前正在尝试使用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)
我知道通常请求使用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?
答案 0 :(得分:1)
您是否尝试使用预期名称调用该文件?
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)