如何在python中异常重试一次

Sla*_*off 6 python exception-handling http python-requests

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

response = requests.post(full_url, json.dumps(data))
Run Code Online (Sandbox Code Playgroud)

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

那个解决方案是:

try:
    response = requests.post(full_url, json.dumps(data))
except RequestException:
    try:
        response = requests.post(full_url, json.dumps(data))
    except:
        continue
Run Code Online (Sandbox Code Playgroud)

有一个更好的方法吗?或者,通常有更好的方法来处理潜在的错误HTTP响应吗?

Ste*_*ski 16

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

如果你需要一个功能:

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
Run Code Online (Sandbox Code Playgroud)

使用这样:

func = lambda:requests.post(full_url, json.dumps(data))
response = multiple_tries(func, 2, RequestException)
Run Code Online (Sandbox Code Playgroud)