我想强制所有请求在5xx HTTP状态码上重试。我会做的是:
retry = requests.packages.urllib3.util.retry.Retry(
total=20,
backoff_factor=0.1,
status_forcelist=[500, 502, 503, 504],
method_whitelist=frozenset(['GET', 'POST']))
for adapter in session.adapters.values():
adapter.max_retries = retry但我需要为现有的代码在不同的模块/包中使用许多不同的会话。他们中的一些人使用s = Session(); s.get(),其他人使用requests.get()。所以,我想强制他们都使用这个Retry实例。
是否可以在requests包级别上(通过初始化、设置、简单的猴子修补requests包)?
import requests
# Initialize/setup/patch requests package.
???
# Following should retry on server errors:
requests.Session().get('http://httpstat.us/500')
requests.post('http://httpstat.us/500', data={})我尝试将requests.adapters.DEFAULT_RETRIES设置为retry object。但这不是它的工作方式...
发布于 2016-08-20 13:24:44
import requests
import logging
logging.basicConfig(level='DEBUG')
def forceretry(max_retries):
""" Decorator for `requests.adapters.HTTPAdapter.__init__`. """
def decorate(func):
def wrapper(self, *args, **kwargs):
func(self, *args, **kwargs)
self.max_retries = max_retries
return wrapper
return decorate
max_retries = requests.packages.urllib3.util.retry.Retry(
total=20,
backoff_factor=0.1,
status_forcelist=[500, 502, 503, 504],
method_whitelist=frozenset(['GET', 'POST']))
func = requests.adapters.HTTPAdapter.__init__
requests.adapters.HTTPAdapter.__init__ = forceretry(max_retries)(func)
requests.post('http://httpstat.us/500', data={})它强制每个会话都使用Retry对象(不会设置默认的会话)。但这对我很管用。
发布于 2016-08-20 17:59:12
我会使用exponential backoff算法。
这里有一个很好的包,它为您提供了一个装饰器:backoff。可以与requests一起使用。
来自包文档的代码示例:
@backoff.on_exception(backoff.expo,
requests.exceptions.RequestException,
max_tries=8)
def get_url(url):
return requests.get(url)https://stackoverflow.com/questions/38987263
复制相似问题