在使用 requests
包发送 POST
请求时,如何实现重试 5 次,间隔 10 秒。
我发现了很多关于 GET
请求的例子,只是 post
没有。
这就是我目前正在使用的,有时我会收到 503 错误。如果我收到错误的响应 HTTP 代码,我只需要实现重试。
for x in final_payload:
post_response = requests.post(url=endpoint, data=json.dumps(x), headers=headers)
#Email me the error
if str(post_response.status_code) not in ["201","200"]:
email(str(post_response.status_code))
最佳答案
你可以使用urllib3.util.retry
模块结合 requests
有如下内容:
from urllib3.util.retry import Retry
import requests
from requests.adapters import HTTPAdapter
def retry_session(retries, session=None, backoff_factor=0.3):
session = session or requests.Session()
retry = Retry(
total=retries,
read=retries,
connect=retries,
backoff_factor=backoff_factor,
method_whitelist=False,
)
adapter = HTTPAdapter(max_retries=retry)
session.mount('http://', adapter)
session.mount('https://', adapter)
return session
用法:
session = retry_session(retries=5)
session.post(url=endpoint, data=json.dumps(x), headers=headers)
注意:您还可以继承自 Retry
类并自定义重试行为和重试间隔。
关于python - 在 Python 中实现请求重试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49121365/