API 调用时无类型

问题描述

使用 http.client 从 Qualtrics 导出调查回复。为了获得我的调查回复,我需要进度 Id...当我创建数据导出时,我能够看到它的结果,但在尝试获取我需要的值时出现 nonetype 错误

import http.client

baseUrl = "https://{0}.qualtrics.com/API/v3/surveys/{1}/export-responses/".format(dataCenter,surveyId)
headers = {
    "content-type": "application/json","x-api-token": apiToken
}
downloadRequestPayload = '{"format":"' + fileFormat + '","useLabels":true}'

downloadRequestResponse = conn.request("POST",baseUrl,downloadRequestPayload,headers)
downloadRequestResponse

{"result":{"progressId":"ES_XXXXXzFLEPYYYYY","percentComplete":0.0,"status":"inProgress"},"Meta":{"requestId":"13958595-XXXX-YYYY-ZZZZ-407d23462XXX","httpStatus":"200 - OK"}}

所以我清楚地看到了我需要的 progressId 值,但是当我尝试获取它时...

progressId = downloadRequestResponse.json()["result"]["progressId"]
AttributeError: 'nonetype' object has no attribute 'json'

(我知道我可以使用 Qualtrics 建议的请求库,但出于我的目的,我需要使用 http.client 或 urllib)

解决方法

请参阅https://docs.python.org/3/library/http.client.html#http.client.HTTPConnection

conn.request 不返回任何内容(在 Python 中,这意味着它返回 None,这就是发生错误的原因)。

要获取响应,请使用 getresponse,它在发送请求后调用时会返回 HTTPResponse 实例。

另外,请注意 HTTPResponse 对象中没有 json 方法。不过,有一个 read 方法。您可能需要使用 json 模块来解析内容。

...
import json
conn.request("POST",baseUrl,downloadRequestPayload,headers)
downloadRequestResponse = conn.getresponse()
content = downloadRequestResponse.read()
result = json.loads(content)