【问题标题】:How to retry just once on exception in python如何在python中的异常重试一次
【发布时间】:2013-08-09 17:41:08
【问题描述】:

我可能以错误的方式处理此问题,但我收到了一个 POST 请求:

response = requests.post(full_url, json.dumps(data))

这可能由于多种原因而失败,有些与数据有关,有些是临时失败,由于端点设计不当,很可能会返回相同的错误(服务器使用无效数据执行不可预测的事情)。为了捕捉这些临时故障并让其他人通过,我认为最好的方法是重试一次,然后在再次引发错误时继续。我相信我可以使用嵌套的 try/except 来做到这一点,但这对我来说似乎是一种不好的做法(如果我想在放弃之前尝试两次怎么办?)

解决方案是:

try:
    response = requests.post(full_url, json.dumps(data))
except RequestException:
    try:
        response = requests.post(full_url, json.dumps(data))
    except:
        continue

有没有更好的方法来做到这一点?或者,是否有更好的方法来处理潜在的错误 HTTP 响应?

【问题讨论】:

    标签: python http exception-handling python-requests


    【解决方案1】:
    for _ in range(2):
        try:
            response = requests.post(full_url, json.dumps(data))
            break
        except RequestException:
            pass
    else:
        raise # both tries failed
    

    如果你需要一个函数:

    def multiple_tries(func, times, exceptions):
        for _ in range(times):
            try:
                return func()
            except Exception as e:
                if not isinstance(e, exceptions):
                    raise # reraises unexpected exceptions 
        raise # reraises if attempts are unsuccessful
    

    这样使用:

    func = lambda:requests.post(full_url, json.dumps(data))
    response = multiple_tries(func, 2, RequestException)
    

    【讨论】:

    • 哦,这要优雅得多。
    • 答案几乎有效,但如果你达到加薪,你会得到“RuntimeError: No active exception to reraise”(也许这曾经在python2中工作?)跨度>
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-02-18
    • 1970-01-01
    • 2011-01-06
    • 1970-01-01
    相关资源
    最近更新 更多