Error: Unauthorized - Python script to IBM Watson Visual Recognition

Error: Unauthorized - Python script to IBM Watson Visual Recognition

所以我试图获取 IBM Visual Recognition Service 的输出,但总是得到相同的错误:{"code":401, "error": "Unauthorized"}

如果我用 cURL 尝试它,它会起作用:

$ curl -X POST -u "apikey: ------------" -F "images_file=@bobross.jpg" "https://gateway.watsonplatform.net/visual-recognition/api/v3/detect_faces?version=2018-03-19"
{ facerecognition data }

到目前为止我的 python 代码:

import json
import sys
import requests
header= { 'apikey': '---------', 'Content-Type': 'FaceCharacteristics'}
url= "https://gateway.watsonplatform.net/visual-recognition/api/v3/detect_faces?version=2018-03-19"
file ={image:open('bobross.jpg','rb')}
r = requests.post(url, headers=header, files=file)
print(r.text)

我在其他变体中尝试了我的代码,但它总是导致 "Unauthorized"。 顺便说一句,我对 python 的经验很少,我仍在努力学习。

在您的 curl 示例中,您使用 -u 标志传递身份验证,而在 python 中,您按原样在 header 中传递它。服务器忽略了 header 中的身份验证,您将如我们所料返回 401。

为了让生活更轻松,我们可以将我们的身份验证详细信息传递到请求本身 auth=('apikey', '[An API Key]') 作为命名参数。

从 header 中删除 Content-Type: FaceCharacteristics 也值得 - 不太确定这是从哪里得到的。

import requests

url = 'https://gateway.watsonplatform.net/visual-recognition/api/v3/classify?version=2018-03-19'
files = {'images_file': open('fruitbowl.jpg','rb')}
resp = requests.post(url, auth=('apikey', '[An API Key]'), files=files)

print(resp.content)

最后添加文件,您应该已经准备就绪。

More info on requests here


但是如果你做的不止这些..

您可能想看看 Python SDK that IBM provides。 它有更多的文档和示例代码供您使用。

例如,这是提供的。

import json
from watson_developer_cloud import VisualRecognitionV3

visual_recognition = = VisualRecognitionV3(
    version='{version}',
    api_key='{api_key}'
)
with open('./fruitbowl.jpg', 'rb') as images_file:
    classes = visual_recognition.classify(
        images_file,
        threshold='0.6',
        classifier_ids='dogsx2018x03x17_1725181949,Connectors_424118776')
print(json.dumps(classes, indent=2))