在 Python 中实现请求的重试 [英] Implementing retry for requests in Python

查看:28
本文介绍了在 Python 中实现请求的重试的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在使用 requests 包发送 POST 请求时,如何实现 5 次间隔 10 秒的重试计数.我找到了很多 GET 请求的例子,而不是 post.

How do I implement a retry count of 5 times, 10 seconds apart when sending a POST request using the requests package. I have found plenty of examples for GET requests, just not post.

这就是我目前正在使用的,有时我会收到 503 错误.如果我收到错误的 HTTP 响应代码,我只需要实现重试.

This is what I am working with at the moment, sometimes I get a 503 error. I just need to implement a retry if I get a bad response HTTP code.

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 结合使用如下:

you can use urllib3.util.retry module in combination with requests to have something as follow:

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 类并自定义重试行为和重试间隔.

NB: You can also inherit from Retry class and customize the retry behavior and retry intervals.

这篇关于在 Python 中实现请求的重试的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆