问题:
测试二进制响应的 API 响应的最简单方法是什么?
上下文:
我有一个函数可以对某些数据进行 API 调用。该 API 调用的响应 ( api_response) 可以是 JSON 或二进制。如果是 JSON,并且如果它包含percent_complete,则数据尚未准备好,我的函数使用percent_completekey:pair 值来更新用户的进度条。
如果响应是 JSON 且包含meta,则我的数据已准备就绪并已作为 JSON 对象返回。
如果响应是二进制的,那么我的数据也已准备好,但已作为.xlsx[二进制]返回。这是数据未准备好时的响应,您将看到percent_complete用于进度条 -
{
"data": {
"id": "2768510",
"type": "jobs",
"attributes": {
"job_type": "PORTFOLIO_VIEW_RESULTS",
"started_at": "2022-04-14T16:19:21Z",
"parameters": {
"end_date": "2022-04-14",
"output_type": "json",
"view_id": 304078,
"portfolio_id": 1,
"portfolio_type": "firm",
"start_date": "2022-04-14"
},
"percent_complete": 0.0,
"status": "In Progress"
},
"relationships": {
"creator": {
"links": {
"self": "/v1/jobs/2768510/relationships/creator",
"related": "/v1/jobs/2768510/creator"
},
"data": {
"type": "users",
"id": "731221"
}
}
},
"links": {
"self": "/v1/jobs/2768510"
}
},
"included": []
Run Code Online (Sandbox Code Playgroud)
当前函数:
以下函数继续每 5 秒调用一次 API(根据self上述 API 对象,使用 中的 7 位代码),直到meta以 JSON 对象返回(因此我的数据作为 JSON 对象返回)并返回JSON 对象为api_response.
否则,API 调用每 5 秒继续一次,并且仅用于percent_complete更新状态栏(使用enlighten库)
def api_call():
# Calling function containing the JOBS API endpoint for calling, until its RESPONSE == data requested.
endpoint_url = endpoint_initializer()
# Calling function containing API credentials
key, secret, url, group_url = ini_reader()
# Setting variable for use in progress bar, used to reflect API 'percent_complete' key pair value.
BAR_FORMAT = u'{id_value} {percentage:3.0f}%|{bar}| ' u'[{elapsed}<{eta}, {rate:.2f} %/s]'
manager = enlighten.get_manager()
date = dt.datetime.today().strftime("%Y-%m-%d")
print("------------------------------------\n","API URL constructed for:", date, "\n------------------------------------")
print("----------------------------------------------------------------------\n","Addepar Endpoint:", endpoint_url, "\n----------------------------------------------------------------------")
# Setting variable with counter for progress bar.
pbar = manager.counter(total=100, bar_format=BAR_FORMAT)
while True:
response = requests.get(url = endpoint_url, auth = HTTPBasicAuth(key, secret), headers = {"Vendor-firm": "665"})
api_response = json.loads(response.text)
if "meta" not in api_response:
id_value = "id"
res1 = [val[id_value] for key, val in api_response.items() if id_value in val]
id_value = "".join(res1)
percent_value = "percent_complete"
res2 = api_response["data"]["attributes"].get("percent_complete", '')*100
pbar.count = res2
pbar.update(incr=0, id_value=id_value)
time.sleep(5)
elif "meta" in api_response:
pbar.count = 100
pbar.update(incr=0, id_value=id_value)
pbar.close()
return api_response
Run Code Online (Sandbox Code Playgroud)
我如何扩展这个函数来测试响应(api_response)是否包含二进制,如果是,那么return api_response?
普通的 http 服务器应该返回适当的内容类型。请检查:
response.headers['content-type']
Run Code Online (Sandbox Code Playgroud)