def query_tf_serving(url, data, request_time, num=1):
"""
请求模型服务接口
Args:
url: 请求url
data: 请求数据,image base64字符串
request_time: 请求时间
num: 请求次数,最多重试5次
Returns:
分类模型预测值
"""
logger.info(f"The {num} query to tensorflow serving. URL: {url}. request_time: {str(request_time)}")
if num >= 5:
raise Exception(f"Query tensorflow serving retry over 5 times.")
header = {
'user-agent': logTag.x_call_id,
"Content-Type": "application/json",
"X-Call-Id": logTag.x_call_id,
"Request-Time": str(request_time)
}
try:
res = requests.post(url=url, data=data, headers=header, timeout=TF_SERVING_TIMEOUT)
if res.status_code != 200:
num += 1
logger.error(f"Query tensorflow serving failed. status_code: {res.status_code}")
sleep(RETRY_SLEEP_TIME)
return query_tf_serving(url, data, request_time, num)
return json.loads(res.text)['predictions']
except Exception as e:
num += 1
logger.error(f"Query tensorflow serving failed. error_message: {e}")
sleep(RETRY_SLEEP_TIME)
return query_tf_serving(url, data, request_time, num)
http请求示例
最新推荐文章于 2023-04-03 16:10:03 发布
该代码段展示了如何使用Python的requests库来调用TensorFlow Serving的预测接口。它包含了错误处理和重试机制,确保请求在遇到问题时能够重新尝试。输入参数包括URL、请求数据(如base64编码的图像)、请求时间和最大重试次数。如果请求失败,会根据HTTP状态码进行重试,直到达到最大重试次数或者成功返回模型预测结果。
摘要由CSDN通过智能技术生成