使用 python 请求时未经授权的 HTTP 请求

unauthorized HTTP request when using python requests

当我尝试使用 curl 的 REST API 时,它运行得非常好。有效的代码如下:

curl -X POST -u "apikey:####My Key####" \
"https://api.eu-gb.natural-language-understanding.watson.cloud.ibm.com/instances/4b490a19-9cd0-4e9b-9f71-c7ce59f9d7df/v1/analyze?version=2019-07-12" \
--request POST \
--header "Content-Type: application/json" \
--data '{
  "text": "I love apples! I do not like oranges.",
  "features": {
    "sentiment": {
      "targets": [
        "apples",
        "oranges",
        "broccoli"
      ]
    },
    "keywords": {
      "emotion": true
    }
  }
}'

但是当我在我的 Python 代码中做同样的事情时,我没有获得身份验证。不确定如何在 python 代码中使用“-u”。

import requests

WATSON_NLP_URL = "https://api.eu-gb.natural-language-understanding.watson.cloud.ibm.com/instances/4b490a19-9cd0-4e9b-9f71-c7ce59f9d7df/v1/analyze?version=2019-07-12"
WATSONAPIKEY = "XXXX"
params = {"apikey":WATSONAPIKEY}
json_to_nlp = {
  "text": "I love apples! I do not like oranges.",
  "features": {
    "sentiment": {
      "targets": [
        "apples",
        "oranges",
        "broccoli"
      ]
    },
    "keywords": {
      "emotion": "true"
    }
  }
}

r = requests.post(url=WATSON_NLP_URL, json=json_to_nlp, params=params)
data = r.json()
print (r)

我收到未授权 (401) 响应:

<Response [401]>

对于curl,-u是添加一个基本的auth header。

所以你想像这样构建请求:

import requests
from requests.auth import HTTPBasicAuth

WATSON_NLP_URL = "https://api.eu-gb.natural-language-understanding.watson.cloud.ibm.com/instances/4b490a19-9cd0-4e9b-9f71-c7ce59f9d7df/v1/analyze?version=2019-07-12"
WATSONAPIKEY = "XXXX"
json_to_nlp = {
  "text": "I love apples! I do not like oranges.",
  "features": {
    "sentiment": {
      "targets": [
        "apples",
        "oranges",
        "broccoli"
      ]
    },
    "keywords": {
      "emotion": "true"
    }
  }
}

r = requests.post(url=WATSON_NLP_URL, json=json_to_nlp, auth=HTTPBasicAuth('apikey', WATSONAPIKEY))
data = r.json()
print (r)