Github sample地址:https://github.com/Azure-Samples/cognitive-services-qnamaker-python/blob/master/documentation-samples/quickstarts/get-answer/get-answer-3x.py
VS Code,anaconda的Python3.7,运行sample遇到错误:
Unexpected error: <class 'socket.gaierror'>
Unexpected error: [Errno 8] nodename nor servname provided, or not known
百度下,很多说host文件等等,仔细查看下,错误其实很简单,是Host地址前面不能带有 "https://"
# Represents the various elements used to create HTTP request URIs
# for QnA Maker operations.
# From Publish Page
# Example: YOUR-RESOURCE-NAME.azurewebsites.net
# CAUTION: This is not the exact value of HOST field
# HOST trimmed to work with http library
host = "YOUR-RESOURCE-NAME.azurewebsites.net";
这个sample,直接输入文中问题,后台服务会不识别:
发送前:encodedQuestion = question.encode("utf-8")
拿到结果后解析:print(json.dumps(json.loads(answer, encoding="utf-8"), ensure_ascii=False, indent=4))
代码:
# -*- coding:utf-8 -*-
import http.client, urllib.parse, json, time, sys
# Represents the various elements used to create HTTP request URIs
# for QnA Maker operations.
# From Publish Page
# Example: YOUR-RESOURCE-NAME.azurewebsites.net
# CAUTION: This is not the exact value of HOST field
# HOST trimmed to work with http library
host = "YOUR-RESOURCE-NAME.azurewebsites.net";
# Authorization endpoint key
# From Publish Page
endpoint_key = "xxx";
# Management APIs postpend the version to the route
# From Publish Page
# Example: /knowledgebases/ZZZ15f8c-d01b-4698-a2de-85b0dbf3358c/generateAnswer
# CAUTION: This is not the exact value after POST
# Part of HOST is prepended to route to work with http library
route = "";
# JSON format for passing question to service
question = "{'question': '天空为什么是蓝色的','top': 3}"
encodedQuestion = question.encode("utf-8")
print(encodedQuestion)
headers = {
'Authorization': 'EndpointKey ' + endpoint_key,
'Content-Type': 'application/json'
}
try:
conn = http.client.HTTPSConnection(host, port=443)
conn.request("POST", route, encodedQuestion, headers)
response = conn.getresponse ()
answer = response.read()
print(json.dumps(json.loads(answer, encoding="utf-8"), ensure_ascii=False, indent=4))
except:
print ("Unexpected error:", sys.exc_info()[0])
print ("Unexpected error:", sys.exc_info()[1])