# coding: utf-8
import requests
from requests.adapters import HTTPAdapter
from urllib3.util import Retry
class RetryRequests(object):
def __init__(self, connect_timeout, read_timeout, max_retry, status_forcelist=None, session=None):
self.session = session or requests.Session()
retry = Retry(
total=max_retry, #最大重试多少次
backoff_factor=0.1, # 每次重试时间间隔(0.1, 0.2, 0.4)
status_forcelist=status_forcelist, # 返回哪些状态码时进行重试
)
adapter = HTTPAdapter(max_retries=retry)
self.session.mount('http://', adapter)
self.session.mount('https://', adapter)
self.timeout = (connect_timeout, read_timeout)
def get(self, url, timeout=None, **kwargs):
if timeout is None:
timeout = self.timeout
return self.session.get(url, timeout=timeout, **kwargs)
def post(self, url, timeout=None, data=None, json_data=None, **kwargs):
if timeout is None:
timeout = self.timeout
return self.session.post(url, timeout=timeout, data=data, json=json_data, **kwargs)
common_request_service = RetryRequests(10, 30, 3, [500, 502, 503, 504])
if __name__ == "__main__":
import time
rr = common_request_service
now = time.time()
try:
print rr.get("http://localhost:8888").text
except Exception as e:
print e
print time.time() - now
requests 超时,返回非500重试的方法
©著作权归作者所有,转载或内容合作请联系作者
- 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
- 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
- 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
推荐阅读更多精彩内容
- 【蝴蝶效应】 蝴蝶效应:上个世纪70年代,美国一个名叫洛伦兹的气象学家在解释空气系统理论时说,亚马逊雨林一只蝴蝶...