0

我目前正在尝试使用 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)

我知道通常 Requests 使用 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?

4

1 回答 1

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)
于 2015-11-25T16:23:36.020 回答