HttpRequest封装--带超时自动重试【转】
代码如下:
import requests import traceback from logging import getLogger logger = getLogger() #打印日志 class Request: def __init__(self, url, params=None, data=None, headers=None, files=None, json=None, timeout=5, retry_tag=False, retry_count=3): self.url = url self.params = params self.data = data self.headers = headers self.files = files self.json = json self.timeout = timeout self.retry_count = retry_count #最大重试次数 self.__req_method = self.__retry if retry_tag else self.__request self.__retry_tag = False #重试标识 def __get_response(self): try: ret = self.response.json() except: logger.warning("接口返回的不是json!无法转成字典!http_status:{},response:{}".format(self.response.status_code, self.response.content)) return {} logger.debug("接口返回数据:{}".format(ret)) return ret def __request(self, method): self.__retry_tag = False try: self.response = requests.request(method, url=self.url, params=self.params, data=self.data, json=self.json, headers=self.headers, files=self.files, verify=False, timeout=self.timeout) except requests.exceptions.Timeout: logger.warning("接口请求超时") self.__retry_tag = True return {} except: # 其他异常 logger.error("接口请求出现异常!错误信息,", traceback.format_exc()) return {} return self.__get_response() def __retry(self, method): for i in range(self.retry_count + 1): # 要循环 if i > 0: logger.info("开始第%s次重试" % i) ret = self.__request(method) if not self.__retry_tag: # 请求成功/出现其他异常,不重试 return ret else: logger.error("超时重试次数超过已经3次") raise Exception("超时重试次数超过已经3次") def get(self): return self.__req_method("get") def post(self): return self.__req_method("post") def put(self): return self.__req_method("put") def delete(self): return self.__req_method("delete") if __name__ == '__main__': r = Request("http://127.0.0.1:5000/") r.get()
本文来自博客园,作者:他还在坚持嘛,转载请注明原文链接:他还在坚持嘛 https://www.cnblogs.com/brf-test/p/15977745.html