如何使python .post()请求重试?

问题描述 投票:21回答:2

我正在尝试在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()请求不会重试。

怎么了?

python python-requests urllib3
2个回答
28
投票

在urllib3中,默认情况下不允许POST作为重试方法(因为它可能导致多次插入)。您可以通过以下方式强制它:

Retry(total=3, method_whitelist=frozenset(['GET', 'POST']))

请参见https://urllib3.readthedocs.io/en/latest/reference/urllib3.util.html#urllib3.util.retry.Retry


0
投票

您可以使用坚韧。

doc:https://tenacity.readthedocs.io/en/latest/

您可以在之前或之后登录

pip install tenacity
import 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")
© www.soinside.com 2019 - 2024. All rights reserved.