在python中如何重试一次异常 [英] How to retry just once on exception in python

查看:1291
本文介绍了在python中如何重试一次异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我可能接近这个错误的方式,但是我有一个POST请求出来:

I might be approaching this the wrong way, but I've got a POST request going out:

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

哪些可能会由于一些原因而失败,一些与数据有关,一些是临时故障,由于设计不当的端点可能会因为相同的错误而返回(服务器使用无效数据做不可预测的事情)。为了抓住这些暂时的失败,让别人通过,我认为最好的方法是重试一次,然后如果再次出现错误,继续。我相信我可以做一个嵌套的尝试/除了,但它似乎是糟糕的做法(如果我想在放弃之前尝试两次?)

Which could potentially fail for a number of reasons, some being related to the data, some being temporary failures, which due to a poorly designed endpoint may well return as the same error (server does unpredictable things with invalid data). To catch these temporary failures and let others pass I thought the best way to go about this would be to retry once and then continue if the error is raised again. I believe I could do it with a nested try/except, but it seems like bad practice to me (what if I want to try twice before giving up?)

解决方案是:

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

有更好的方法吗?另外还有一种更好的方法来处理可能出现的HTTP响应错误?

Is there a better way to do this? Alternately is there a better way in general to deal with potentially faulty HTTP responses?

推荐答案

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

如果您需要一个功能这个:

If you need a function for this:

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)

这篇关于在python中如何重试一次异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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