<<返回python首页 python

《Python 应用案例》

Python重试场景的解决方案

成功,动机、解决方案、营销工作

在使用Python的时候常会遇到的问题就是,某个方法出现了异常,重试几次。循环重复一个方法是很常见的。尤其在爬虫中的获取代理,对获取失败的情况进行重试。能实现重试机制的三方库有如retryingtenacity等库。本节tenacity为例,来实现了几乎我们可以使用到的所有重试场景,如:

  1. 在什么情况下才进行重试?
  2. 重试几次呢?
  3. 重试多久后结束?
  4. 每次重试的间隔多长呢?
  5. 重试失败后的回调?

在使用它之前 ,先要安装它

!pip3 install tenacity -i https://pypi.tuna.tsinghua.edu.cn/simple

最基本的重试

无条件重试,重试之间无间隔。

运行后会进入死机状态,需刷新页面

from tenacity import retry 

@retry 
def test_retry(): 
    print("等待重试,重试无间隔执行...") 
    raise Exception 

test_retry() 

无条件重试,但是在重试之前要等待 2 秒

运行后会进入死机状态,需刷新页面

from tenacity import retry, wait_fixed 

@retry(wait=wait_fixed(2)) 
def test_retry(): 
    print("等待重试...") 
    raise Exception 

test_retry() 

2. 设置停止基本条件

只重试7 次

from tenacity import retry, stop_after_attempt 

@retry(stop=stop_after_attempt(7)) 
def test_retry(): 
    print("等待重试...") 
    raise Exception 

test_retry() 

重试 10 秒后不再重试

from tenacity import retry, stop_after_delay 

@retry(stop=stop_after_delay(10)) 
def test_retry(): 
    print("等待重试...") 
    raise Exception 

test_retry() 

或者上面两个条件满足一个就结束重试

from tenacity import retry, stop_after_delay, stop_after_attempt 

@retry(stop=(stop_after_delay(10) | stop_after_attempt(7))) 
def test_retry(): 
    print("等待重试...") 
    raise Exception 

test_retry() 

3. 设置何时进行重试

在出现特定错误/异常(比如请求超时)的情况下,再进行重试

from requests import exceptions 
from tenacity import retry, retry_if_exception_type 

@retry(retry=retry_if_exception_type(exceptions.Timeout)) 
def test_retry(): 
    print("等待重试...") 
    raise exceptions.Timeout 

test_retry() 

在满足自定义条件时,再进行重试。

如下示例,当 test_retry 函数返回值为 False 时,再进行重试

from tenacity import retry, stop_after_attempt, retry_if_result 

def is_false(value): 
    return value is False 

@retry(stop=stop_after_attempt(3), 
       retry=retry_if_result(is_false)) 
def test_retry(): 
    return False 

test_retry() 

4. 重试后错误重新抛出

当出现异常后,tenacity 会进行重试,若重试后还是失败,默认情况下,往上抛出的异常会变成 RetryError,而不是最根本的原因。

因此可以加一个参数(reraise=True),使得当重试失败后,往外抛出的异常还是原来的那个。

from tenacity import retry, stop_after_attempt 

@retry(stop=stop_after_attempt(7), reraise=True) 
def test_retry(): 
    print("等待重试...") 
    raise Exception 

test_retry() 

5. 设置回调函数

当最后一次重试失败后,可以执行一个回调函数

from tenacity import * 

def return_last_value(retry_state): 
    print("执行回调函数") 
    return retry_state.outcome.result()  # 表示返回原函数的返回值 

def is_false(value): 
    return value is False 

@retry(stop=stop_after_attempt(3), 
       retry_error_callback=return_last_value, 
       retry=retry_if_result(is_false)) 
def test_retry(): 
    print("等待重试中...") 
    return False 

print(test_retry()) 

总结

本节介绍了Python重试场景的第三方库的解决方案,其中涉及到了装饰器和及回调函数。相关Python基础的课程请参照本站的Python3教程。

移动端设备除iPad Pro外,其它移动设备仅能阅读基础的文本文字。
建议使用PC或笔记本电脑,浏览器使用Chrome或FireFox进行浏览,以开启左侧互动实验区来提升学习效率,推荐使用的分辨率为1920x1080或更高。
我们坚信最好的学习是参与其中这一理念,并致力成为中文互联网上体验更好的学练一体的IT技术学习交流平台。
您可加QQ群:575806994,一起学习交流技术,反馈网站使用中遇到问题。
内容、课程、广告等相关合作请扫描右侧二维码添加好友。

狐狸教程 Copyright 2021

进入全屏