python 代码的订阅密钥无效,但相同的密钥在 westus.dev.cognitive.microsoft.com 上工作正常

Invalid Subscription Key for python code but same key is working fine on westus.dev.cognitive.microsoft.com

我刚刚开始使用 Microsoft 的计算机视觉 OCR api,订阅密钥和图像 url 在 https://westus.dev.cognitive.microsoft.com/docs/services/56f91f2d778daf23d8ec6739/operations/56f91f2e778daf14a499e1fc/console

上运行良好

但是我在使用 python 代码时出现以下错误

{"statusCode": 401, "message": "Access denied due to invalid subscription key. Make sure to provide a valid key for an active subscription."}

我已经尽力找出错误但失败了。

我做错了什么?

提前致谢。

import httplib, urllib, base64

headers = {
    # Request headers
    'Content-Type': 'application/json',
    'Ocp-Apim-Subscription-Key': '{1111460aa78d4b27****************}',
}

params = urllib.urlencode({
    # Request parameters
    'language': 'unk',
    'detectOrientation ': 'true',
})

try:
    conn = httplib.HTTPSConnection('westus.api.cognitive.microsoft.com')
    conn.request("POST", "/vision/v1.0/ocr?%s" % params, "{\"url\":\"https://s-media-cache-ak0.pinimg.com/originals/fb/e6/56/fbe65691cb66c6f035a859d9671c3fe5.jpg\"}", headers)
    response = conn.getresponse()
    data = response.read()
    print(data)
    conn.close()
except Exception as e:
    print("[Errno {0}] {1}".format(e.errno, e.strerror))

您需要删除 API 键值的大括号,即:

headers = {
    # Request headers
    'Content-Type': 'application/json',
    'Ocp-Apim-Subscription-Key': '1111460aa78d4b27****************',
}