【问题标题】:POST request to IBM Watson Relationship extraction returns error对 IBM Watson 关系提取的 POST 请求返回错误
【发布时间】:2015-03-09 10:37:50
【问题描述】:

在 Bluemix 中,我尝试从 Python 调用 IBM Watson 关系提取 API。首先,我在 Bluemix 上创建一个应用程序并将关系提取器 api 绑定到它。然后从 API 的下拉菜单中,我从实例化凭据中获取用户名和密码。在下面的 coe 中,我已将其替换为 bluemux-usernamebluemix-password。我为此编写的 Python 代码如下:

import requests
import json

url="https://gateway.watsonplatform.net/relationship-extraction-beta/api/v1/sire/0"
username="bluemix_username"
password="bluemix_passowrd"
with open ("data.txt", "r") as myfile:
    text=myfile.read().replace('\n', '')

raw_data = {
    'contentItems' : [{
        'contenttype' : 'text/plain',
        'content': text
    }]
}

input_data = json.dumps(raw_data)


response = requests.post(url, auth=(username, password), headers =   {'content-type': 'application/json'}, data=input_data)
try:
    response.raise_for_status()
except requests.exceptions.HTTPError as e:
    print("And you get an HTTPError: %s"% e.message)

但是,当我运行它时,我收到以下错误:

And you get an HTTPError: 400 Client Error: Bad Request

*注意:我对个性洞察 API 使用了相同的方法,并且效果很好。

有什么想法吗?

谢谢

【问题讨论】:

  • API 文档 (ibm.com/smarterplanet/us/en/ibmwatson/developercloud/apis/#!/…) 说用于关系提取的 HTTP 方法是 GET,并且需要一个强制参数 txt
  • 感谢您的回复@kedar,我尝试了以下response = requests.get(url, auth=(username, password), headers = {'content-type': 'text/plain'}, data=text) 并得到了`你得到一个 HTTPError: 400 Client Error: Error`
  • 改用requests.get(url+'?txt='+text, auth=(username, password))
  • 谢谢,但同样的错误。
  • 您是否更改了文档中指定的网址?

标签: python ibm-cloud ibm-watson


【解决方案1】:

这是您的代码的更新副本,应该可以工作:

import requests
import json

url="https://gateway.watsonplatform.net/relationship-extraction-beta/api/v1/sire/0"
username="bluemix_username"
password="bluemix_passowrd"
with open ("data.txt", "r") as myfile:
    text=myfile.read().replace('\n', '')

input_data = {
    'sid' : 'ie-en-news',
    'txt' : text
}

response = requests.post(url, auth=(username, password), data=input_data)
try:
    response.raise_for_status()
    print response.text
except requests.exceptions.HTTPError as e:
    print("And you get an HTTPError: %s"% e.message)

基本上我更改了您发布的有效负载以添加一些缺失值。

希望这会有所帮助!

【讨论】:

    【解决方案2】:

    如果您不想使用data.txt 并在终端中使用标准输入,您可以这样做:

    ## -*- coding: utf-8 -*-
    
    import os
    import requests
    import fileinput
    
    class RelationshipExtractionService:
        url = None
    
        def __init__(self):
            self.url = "https://gateway.watsonplatform.net/relationship-extraction-beta/api/v1/sire/0"
            self.user = "<username>"
            self.password = "<password>"
    
        def extract(self, text):
            data = {
                'txt': text,
                'sid': 'ie-en-news',  # English News, for Spanish use: ie-es-news
                'rt': 'xml',
            }
    
            r = requests.post(self.url,
                              auth=(self.user, self.password),
                              headers = {
                                  'content-type': 'application/x-www-form-urlencoded'},
                              data=data
                              )
            print("Request sent. Status code: %d, content-type: %s" %
                  (r.status_code, r.headers['content-type']))
            if r.status_code != 200:
                print("Result %s" % r.text)
                raise Exception("Error calling the service.")
            return r.text
    
    if __name__ == '__main__':
        service = RelationshipExtractionService()
        for line in fileinput.input():
            print service.extract(line)
    

    用法

    简单文本分析:
    echo "New York is awesome" | python main.py

    您还可以通过管道传输文件:
    cat article.txt | python main.py

    从 .txt 到 .xml:
    cat article.txt | python main.py &gt; article.xml

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-06-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-08-11
      相关资源
      最近更新 更多