我正在尝试用Python实现请求重试。
它的工作方式类似于.get()请求,但是.post()请求永远不会重试,而不管状态代码是什么。我想在.post()请求中使用它。
我的代码:
from requests.packages.urllib3.util import Retry
from requests.adapters import HTTPAdapter
from requests import Session, exceptions
s = Session()
s.mount('http://', HTTPAdapter(max_retries=Retry(total=2, backoff_factor=1, status_forcelist=[ 500, 502, 503, 504, 521])))
r = s.get('http://httpstat.us/500')
r2 = s.post('http://httpstat.us/500')因此,.get()请求会重试,而.post()请求不会重试。
怎么了?
发布于 2016-03-01 03:16:25
在urllib3中,默认情况下不允许将POST作为重试方法(因为它可能导致多次插入)。不过,您可以强制执行:
Retry(total=3, allowed_methods=frozenset(['GET', 'POST']))请参阅https://urllib3.readthedocs.io/en/latest/reference/urllib3.util.html#urllib3.util.retry.Retry
发布于 2020-02-21 19:31:48
你可以使用坚韧。
文档:https://tenacity.readthedocs.io/en/latest/
你可以在登录之前或之后登录
pip install tenacityimport logging
logging.basicConfig(stream=sys.stderr, level=logging.DEBUG)
logger = logging.getLogger(__name__)
@retry(stop=stop_after_attempt(3), before=before_log(logger, logging.DEBUG))
def post_something():
# post
raise MyException("Fail")https://stackoverflow.com/questions/35704392
复制相似问题