http请求示例

该代码段展示了如何使用Python的requests库来调用TensorFlow Serving的预测接口。它包含了错误处理和重试机制,确保请求在遇到问题时能够重新尝试。输入参数包括URL、请求数据(如base64编码的图像)、请求时间和最大重试次数。如果请求失败,会根据HTTP状态码进行重试,直到达到最大重试次数或者成功返回模型预测结果。
摘要由CSDN通过智能技术生成
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)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值