request请求返回失败自动尝试重连

2021-11-12  本文已影响0人  Chaweys

#请求返回失败后尝试重复连接
def conn_try_again(func):
    nums = 0
    def wrapped(*args,**kwargs):
        try:
            return func(*args,**kwargs)
        except Exception as e:
            nonlocal nums
            if int(nums) < 100:  #循环100次
                nums = nums + 1
                time.sleep(1)
                return wrapped(*args,**kwargs)
            else:
                raise Exception(e)
                with open(log_path,'w',encoding="utf-8") as f:
                    f.write(e)
    return wrapped
    
   
#请求的方法
@conn_try_again
def requestTest(url):
    try:
        result = request.get(url)
    except Exception as e:
        logging.error(e)
    
    return result
上一篇 下一篇

猜你喜欢

热点阅读