Bluemix/Watson Concept Insights APIと対話する一連の Python 関数を作成しました。トークンを生成し、それを使用してサーバーから結果を取得することはできますが、結果は悪臭を放ちます。同じ情報をSwagger テスト ユーティリティにプラグインしたときに得られるものほど良くはありません。
リクエストの送信方法に問題があると思われますが、何が原因かわかりません。コードは次のとおりです。まず、からevent_insight_lib.py
:
def importCredentials(filename='credentials.json'):
if filename in [f for f in os.listdir('.') if os.path.isfile(f)]:
data = json.load(open(filename))['concept_insights'][0]['credentials']
return data
def generateToken(filename='credentials.json'):
credentials = importCredentials(filename)
r = requests.get("https://gateway.watsonplatform.net/authorization/api/v1/token\?url=https://stream.watsonplatform.net/concept-insights/api", auth=(credentials['username'], credentials['password']))
if r.status_code == requests.codes.ok:
return r.text
def annotateText(text, token, content_type = 'text/plain'):
base_url='https://watson-api-explorer.mybluemix.net/concept-insights/api/v2/graphs/wikipedia/en-20120601/annotate_text'
headers = {'X-Watson-Authorization-Token': token, 'Content-Type': content_type}
r = requests.post(base_url, headers=headers, data={'body': text})
return r.text
これらのメソッドは次によって実行されevent_insight.py
ます。
token = event_insight_lib.generateToken()
ret = event_insight_lib.annotateText("""long string being concept-analyzed...""", token)
print(ret)
出力の違いの完全なデモンストレーションはこちらです。完全なコードベースはこちらです。私は Requests ライブラリの経験があまりありません: Pythonic 側のどこかに微妙な間違いがありますか?
IBM のドキュメントの関連部分はここにあります。