手把手教你实现Python重试、超时装饰器

大模型API调用实战:60行Python实现重试、超时与降级策略 在分布式系统和微服务架构中,网络请求的可靠性是工程实践的核心挑战。其原理在于通过客户端策略应对外部服务的不稳定性,技术价值体现在提升系统可用性与用户体验。应用场景广泛覆盖API调用、服务间通信等关键链路。本文聚焦大语言模型(LLM)API集成,针对网络波动、服务限流等常见问题,深入解析如何通过指数退避重试、超时控制及降级方案构建韧性机制,并提供一个即插即用的Python装饰器实现,助力开发者快速提升生产环境稳定性。 阅读详情

一、前言

在写业务代码时候,有许多场景需要重试某块业务逻辑,例如网络请求、购物下单等,希望发生异常的时候多重试几次。本文分享如何利用Python 的装饰器来进行面向切面(AOP)的方式实现自动重试器。

二、简单分析

一个重试装饰器,最重要的就是发生意外异常处理失败自动重试,有如下几点需要注意

  • 失败不能一直重试,因为可能会出现死循环浪费资源,因此需要有 最大重试次数 或者 最大超时时间

  • 不能重试太频繁,因为太频繁容易导致重试次数很快用完,却没有成功响应,需要有 重试时间间隔 来限制,有时可以加大成功概率,例如网络请求时有一段时间是堵塞的,或者对方服务负载太高导致一段时间无法响应等。

简单分析完,我们的重试装饰器,就要支持可配置最大重试次数、最大超时时间、重试间隔,所以装饰器就要设计成带参数装饰器。

三、代码模拟实现

重试装饰器-初版

分析完毕后,看看第一版的装饰器

import time

from functools import wraps

def task_retry(max_retry_count: int = 5, time_interval: int = 2):
    """
    任务重试装饰器
    Args:
        max_retry_count: 最大重试次数 默认5次
        time_interval: 每次重试间隔 默认2s
    """

    def _task_retry(task_func):

        @wraps(task_func)
        def wrapper(*args, **kwargs):
            # 函数循环重试
            for retry_count in range(max_retry_count):
                print(f"execute count {retry_count + 1}")
                try:
                    task_result = task_func(*args, **kwargs)
                    return task_result
                except Exception as e:
                    print(f"fail {str(e)}")
                    time.sleep(time_interval)

        return wrapper

    return _task_retry
          

装饰器内部闭包,就简单通过 for 循环 来执行指定重试次数,成功获取结果就直接 return 返回,发生异常则睡眠配置重试间隔时间后继续循环

写个例子来模拟测试下看看效果

@task_retry()
def user_place_order():
    print("user place order success")
    return {"code": 0, "msg": "ok"}


ret = user_place_order()
print(ret)

>>>out
execute count 1
user place order success
{'code': 0, 'msg': 'ok'}

没有异常正常执行,在函数中模拟一个异常来进行重试看看

@task_retry(max_retry_count=3, time_interval=1)
def user_place_order():
    a = 1 / 0
    print("user place order success")
    return {"code": 0, "msg": "ok"}


ret = user_place_order()
print("user place order ret", ret)

>>>out
fail division by zero
execute count 2
fail division by zero
execute count 3
fail division by zero
user place order ret None
    

可以看到 user_place_order 函数执行了三遍,都发生了除零异常,最后超过最大执行次数,返回了 None 值,我们可以在主逻辑中来判断返回值是否为 None 来进行超过最大重试次数失败的业务逻辑处理

ret = user_place_order()
print("user place order ret", ret)

if not ret:
    print("user place order failed")
    ...

重试装饰器-改进版

现在只能配置 最大重试次数 没有最大超时时间,有时候我们想不但有重试,还得在规定时间内完成,不想浪费太多试错时间。所以增加一个 最大超时时间配置选项默认为None,有值时超过最大超时时间退出重试。

def task_retry(max_retry_count: int = 5, time_interval: int = 2, max_timeout: int = None):
    """
    任务重试装饰器
    Args:
        max_retry_count: 最大重试次数 默认 5 次
        time_interval: 每次重试间隔 默认 2s
        max_timeout: 最大超时时间,单位s 默认为 None,
    """

    def _task_retry(task_func):

        @wraps(task_func)
        def wrapper(*args, **kwargs):
            # 函数循环重试
            start_time = time.time()
            for retry_count in range(max_retry_count):
                print(f"execute count {retry_count + 1}")
                use_time = time.time() - start_time
                if max_timeout and use_time > max_timeout:
                    # 超出最大超时时间
                    print(f"execute timeout, use time {use_time}s, max timeout {max_timeout}")
                    return

                try:
                    return task_func(*args, **kwargs)
                except Exception as e:
                    print(f"fail {str(e)}")
                    time.sleep(time_interval)

        return wrapper

    return _task_retry

看看效果

# 超时
@task_retry(max_retry_count=3, time_interval=1, max_timeout=2)
def user_place_order():
    a = 1 / 0
    print("user place order success")
    return {"code": 0, "msg": "ok"}

>>>out
execute count 1
fail division by zero
execute count 2
fail division by zero
execute count 3
execute timeout, use time 2.010528802871704s, max timeout 2
user place order ret None

# 超过最大重试次数
@task_retry(max_retry_count=3, time_interval=1)
def user_place_order():
    a = 1 / 0
    print("user place order success")
    return {"code": 0, "msg": "ok"}

>>>out
execute count 1
fail division by zero
execute count 2
fail division by zero
execute count 3
fail division by zero
user place order ret None

# 正常
@task_retry(max_retry_count=3, time_interval=1, max_timeout=2)
def user_place_order():
    # a = 1 / 0
    print("user place order success")
    return {"code": 0, "msg": "ok"}

>>>out
execute count 1
user place order success
user place order ret {'code': 0, 'msg': 'ok'}

重试装饰器-加强版

到这重试装饰器基本功能就实现了,但还可以加强,Python现在支持 async 异步方式写法,因此要是可以兼容异步写法那就更好了。先看看装饰异步函数会是什么样的效果

import time
import asyncio
import functools

def task_retry(max_retry_count: int = 5, time_interval: int = 2, max_timeout: int = None):
    """
    任务重试装饰器
    Args:
        max_retry_count: 最大重试次数 默认 5 次
        time_interval: 每次重试间隔 默认 2s
        max_timeout: 最大超时时间,单位s 默认为 None,
    """

    def _task_retry(task_func):

        @wraps(task_func)
        def wrapper(*args, **kwargs):
            # 函数循环重试
            start_time = time.time()
            for retry_count in range(max_retry_count):
                print(f"execute count {retry_count + 1}")
                use_time = time.time() - start_time
                if max_timeout and use_time > max_timeout:
                    # 超出最大超时时间
                    print(f"execute timeout, use time {use_time}s, max timeout {max_timeout}")
                    return

                try:
                    return task_func(*args, **kwargs)
                except Exception as e:
                    print(f"fail {str(e)}")
                    time.sleep(time_interval)

        return wrapper

    return _task_retry
    
    
@task_retry(max_retry_count=3, time_interval=1, max_timeout=2)
def user_place_order():
    # a = 1 / 0
    print("user place order success")
    return {"code": 0, "msg": "ok"}

    
@task_retry(max_retry_count=3, time_interval=2, max_timeout=5)
async def user_place_order_async():
    """异步函数重试案例"""
    a = 1 / 0
    print("user place order success")
    return {"code": 0, "msg": "ok"}

async def main():

    # 同步案例
    # ret = user_place_order()
    # print(f"user place order ret {ret}")

    # 异步案例
    ret = await user_place_order_async()
    print(f"user place order ret {ret}")

if __name__ == '__main__':
    asyncio.run(main())

# 正常时候
execute count 1
user place order success
user place order ret {'code': 0, 'msg': 'ok'}

# 异常时候
>>>out
execute count 1
Traceback (most recent call last):
  File "G:/code/python/py-tools/decorator/base.py", line 138, in <module>
    asyncio.run(main())
  File "G:\softs\DevEnv\python-3.7.9\lib\asyncio\runners.py", line 43, in run
    return loop.run_until_complete(main)
  File "G:\softs\DevEnv\python-3.7.9\lib\asyncio\base_events.py", line 587, in run_until_complete
    return future.result()
  File "G:/code/python/py-tools/decorator/base.py", line 133, in main
    ret = await user_place_order_async()
  File "G:/code/python/py-tools/decorator/base.py", line 121, in user_place_order_async
    a = 1 / 0
ZeroDivisionError: division by zero

Process finished with exit code 1

发现发生异常的时候并没有重试,为什么呢?其实在执行 task_func() 它并没有真正的执行内部逻辑,而是返回一个 coroutine 协程对象,并不会报异常,所以再装饰器中执行一遍就成功就出来了,外面 ret = await user_place_order_async(), 后才真正的等待执行,然后执行函数内的逻辑再报异常就没有捕获到。我们可以打断点验证下

这样装饰器就不支持异步函数的重试,需要加强它,可以使用 asyncio.iscoroutinefunction() 来进行异步函数的判断, 然后再加一个异步函数的闭包就可以实现异步、同步函数都兼容的重试装饰器。

def task_retry(max_retry_count: int = 5, time_interval: int = 2, max_timeout: int = None):
    """
    任务重试装饰器
    Args:
        max_retry_count: 最大重试次数 默认 5 次
        time_interval: 每次重试间隔 默认 2s
        max_timeout: 最大超时时间,单位s 默认为 None,
    """

    def _task_retry(task_func):

        @functools.wraps(task_func)
        def sync_wrapper(*args, **kwargs):
            # 同步循环重试
            start_time = time.time()
            for retry_count in range(max_retry_count):
                print(f"execute count {retry_count + 1}")
                use_time = time.time() - start_time
                if max_timeout and use_time > max_timeout:
                    # 超出最大超时时间
                    print(f"execute timeout, use time {use_time}s, max timeout {max_timeout}")
                    return

                try:
                    task_ret = task_func(*args, **kwargs)
                    return task_ret
                except Exception as e:
                    print(f"fail {str(e)}")
                    time.sleep(time_interval)

        @functools.wraps(task_func)
        async def async_wrapper(*args, **kwargs):
            # 异步循环重试
            start_time = time.time()
            for retry_count in range(max_retry_count):
                print(f"execute count {retry_count + 1}")
                use_time = time.time() - start_time
                if max_timeout and use_time > max_timeout:
                    # 超出最大超时时间
                    print(f"execute timeout, use time {use_time}s, max timeout {max_timeout}")
                    return

                try:
                    return await task_func(*args, **kwargs)
                except Exception as e:
                    print(f"fail {str(e)}")
                    await asyncio.sleep(time_interval)

        # 异步函数判断
        wrapper_func = async_wrapper if asyncio.iscoroutinefunction(task_func) else sync_wrapper
        return wrapper_func

    return _task_retry

注意时间等待 await asyncio.sleep(time_interval) 会导致函数挂起,程序不会在这里等待,而是去事件循环loop中执行其他的已经就绪的任务,如果其他函数运行时间太久了才切换回来,会导致时间超时,换成 time.sleep()的话其实也没有用,如果函数内部还有异步函数执行还是会切换出去,因此异步的时候感觉超时参数意义不大。

模拟测试下

@task_retry(max_retry_count=5, time_interval=2, max_timeout=5)
async def user_place_order_async():
    """异步函数重试案例"""
    a = 1 / 0
    print("user place order success")
    return {"code": 0, "msg": "ok"}

async def io_test():
    """模拟io阻塞"""
    print("io test start")
    time.sleep(3)
    print("io test end")
    return "io test end"

async def main():
    # 同步案例
    # ret = user_place_order()
    # print(f"user place order ret {ret}")

    # 异步案例
    # ret = await user_place_order_async()
    # print(f"user place order ret {ret}")

    # 并发异步
    order_ret, io_ret = await asyncio.gather(
        user_place_order_async(),
        io_test(),
    )
    print(f"io ret {io_ret}")
    print(f"user place order ret {order_ret}")

if __name__ == '__main__':
    asyncio.run(main())
    
    
 >>>out
execute count 1
fail division by zero
io test start
io test end
execute count 2
fail division by zero
execute count 3
execute timeout, use time 5.015768527984619s, max timeout 5
io ret io test end
user place order ret None

可以看出执行一遍后自动切换到了 io_test 中执行由于 io test 中的 time.sleep(3) 会导致整个线程阻塞,一定要等到io_test执行完后才会切换回去,然后再执行两遍就超时了,你可能会说都用异步的库,是的异步的库是可以加速,但我想表达就是这时候统计的耗时是整个程序的而不是单独一个函数的。大家可以在评论区帮我想想有没有其他的方法,要么就不要用这个超时参数。

可以兼容异步函数、然后超时参数可以不配置,影响不大,O(∩_∩)O~

重试装饰器-最终版

最终版就是利用抛异常的方式来结束超过最大重试次数、最大超时,而不是直接返回None,然后再添加一个可配置捕获指定异常的参数,当发生特定异常的时候才重试。

import time
import asyncio
import functools
from typing import Type

class MaxRetryException(Exception):
    """最大重试次数异常"""
    pass

class MaxTimeoutException(Exception):
    """最大超时异常"""
    pass

def task_retry(
        max_retry_count: int = 5,
        time_interval: int = 2,
        max_timeout: int = None,
        catch_exc: Type[BaseException] = Exception
):
    """
    任务重试装饰器
    Args:
        max_retry_count: 最大重试次数 默认 5 次
        time_interval: 每次重试间隔 默认 2s
        max_timeout: 最大超时时间,单位s 默认为 None,
        catch_exc: 指定捕获的异常类用于特定的异常重试 默认捕获 Exception
    """

    def _task_retry(task_func):

        @functools.wraps(task_func)
        def sync_wrapper(*args, **kwargs):
            # 函数循环重试
            start_time = time.time()
            for retry_count in range(max_retry_count):
                print(f"execute count {retry_count + 1}")
                use_time = time.time() - start_time
                if max_timeout and use_time > max_timeout:
                    # 超出最大超时时间
                    raise MaxTimeoutException(f"execute timeout, use time {use_time}s, max timeout {max_timeout}")

                try:
                    task_ret = task_func(*args, **kwargs)
                    return task_ret
                except catch_exc as e:
                    print(f"fail {str(e)}")
                    time.sleep(time_interval)
            else:
                # 超过最大重试次数, 抛异常终止
                raise MaxRetryException(f"超过最大重试次数失败, max_retry_count {max_retry_count}")

        @functools.wraps(task_func)
        async def async_wrapper(*args, **kwargs):
            # 异步循环重试
            start_time = time.time()
            for retry_count in range(max_retry_count):
                print(f"execute count {retry_count + 1}")
                use_time = time.time() - start_time
                if max_timeout and use_time > max_timeout:
                    # 超出最大超时时间
                    raise MaxTimeoutException(f"execute timeout, use time {use_time}s, max timeout {max_timeout}")

                try:
                    return await task_func(*args, **kwargs)
                except catch_exc as e:
                    print(f"fail {str(e)}")
                    await asyncio.sleep(time_interval)
            else:
                # 超过最大重试次数, 抛异常终止
                raise MaxRetryException(f"超过最大重试次数失败, max_retry_count {max_retry_count}")

        # 异步函数判断
        wrapper_func = async_wrapper if asyncio.iscoroutinefunction(task_func) else sync_wrapper
        return wrapper_func

    return _task_retry

@task_retry(max_retry_count=3, time_interval=1, catch_exc=ZeroDivisionError,max_timeout=5)
def user_place_order():
    a = 1 / 0
    print("user place order success")
    return {"code": 0, "msg": "ok"}

@task_retry(max_retry_count=5, time_interval=2, max_timeout=5)
async def user_place_order_async():
    """异步函数重试案例"""
    a = 1 / 0
    print("user place order success")
    return {"code": 0, "msg": "ok"}

async def io_test():
    """模拟io阻塞"""
    print("io test start")
    time.sleep(3)
    print("io test end")
    return "io test end"

async def main():
    # 同步案例
    try:
        ret = user_place_order()
        print(f"user place order ret {ret}")
    except MaxRetryException as e:
        # 超过最大重试次数处理
        print("MaxRetryException", e)
    except MaxTimeoutException as e:
        # 超过最大超时处理
        print("MaxTimeoutException", e)

    # 异步案例
    # ret = await user_place_order_async()
    # print(f"user place order ret {ret}")

    # 并发异步
    # order_ret, io_ret = await asyncio.gather(
    #     user_place_order_async(),
    #     io_test(),
    # )
    # print(f"io ret {io_ret}")
    # print(f"user place order ret {order_ret}")

if __name__ == '__main__':
    asyncio.run(main())

测试捕获指定异常

# 指定捕获除零错误,正常捕获重试
@task_retry(max_retry_count=3, time_interval=1, catch_exc=ZeroDivisionError)
def user_place_order():
    a = 1 / 0
    # a = []
    # b = a[0]
    print("user place order success")
    return {"code": 0, "msg": "ok"}
 

# out
execute count 1
fail division by zero
execute count 2
fail division by zero
execute count 3
fail division by zero
MaxRetryException 超过最大重试次数失败, max_retry_count 3

# 指定捕获除零错误,报索引越界错误,未正常捕获重试,直接退出
@task_retry(max_retry_count=3, time_interval=1, catch_exc=ZeroDivisionError)
def user_place_order():
    # a = 1 / 0
    a = []
    b = a[0]
    print("user place order success")
    return {"code": 0, "msg": "ok"}
 

# out
Traceback (most recent call last):
  File "G:/code/python/py-tools/decorator/base.py", line 184, in <module>
    asyncio.run(main())
  File "G:\softs\DevEnv\python-3.7.9\lib\asyncio\runners.py", line 43, in run
    return loop.run_until_complete(main)
  File "G:\softs\DevEnv\python-3.7.9\lib\asyncio\base_events.py", line 587, in run_until_complete
    return future.result()
  File "G:/code/python/py-tools/decorator/base.py", line 161, in main
    ret = user_place_order()
  File "G:/code/python/py-tools/decorator/base.py", line 97, in sync_wrapper
    task_ret = task_func(*args, **kwargs)
  File "G:/code/python/py-tools/decorator/base.py", line 137, in user_place_order
    b = a[0]
IndexError: list index out of range

Process finished with exit code 1

用抛异常的方式推出更好知道是因为什么原因退出来进行对应的业务逻辑处理。乍一看兼容异步、同步函数导致这个装饰器有点代码冗余,看看大家有没有更好的办法。

到这就结束了,虽然是一个简单的装饰器,但本文还是引伸出很多知识点,望可以帮助到大家。

修改记录

2023-05-01

  • 把重试里的超时计算单独抽离出来,这样功能不会太藕合,分两个装饰器实现
  • 超时装饰器
    • 同步函数的实现在unix内核上可以使用系统信号机制实现超时检测,也可以通过futures.ThreadPoolExecutor 线程去实现超时计算
    • 异步函数则是直接使用 asyncio.wait_for 实现
def set_timeout(timeout: int, use_signal=False):
    """
    超时处理装饰器
    Args:
        timeout: 超时时间,单位秒
        use_signal: 使用信号量机制只能在 unix内核上使用,默认False

    Raises:
        TimeoutException

    """

    def _timeout(func: Callable):

        def _handle_timeout(signum, frame):
            raise MaxTimeoutException(f"Function timed out after {timeout} seconds")

        @functools.wraps(func)
        def sync_wrapper(*args, **kwargs):
            # 同步函数处理超时
            if use_signal:
                # 使用信号量计算超时
                signal.signal(signal.SIGALRM, _handle_timeout)
                signal.alarm(timeout)
                try:
                    return func(*args, **kwargs)
                finally:
                    signal.alarm(0)
            else:
                # 使用线程
                with ThreadPoolExecutor() as executor:
                    future = executor.submit(func, *args, **kwargs)
                    try:
                        return future.result(timeout)
                    except TimeoutError:
                        raise MaxTimeoutException(f"Function timed out after {timeout} seconds")

        @functools.wraps(func)
        async def async_wrapper(*args, **kwargs):
            # 异步函数处理超时
            try:
                ret = await asyncio.wait_for(func(*args, **kwargs), timeout)
                return ret
            except asyncio.TimeoutError:
                raise MaxTimeoutException(f"Function timed out after {timeout} seconds")

        return async_wrapper if asyncio.iscoroutinefunction(func) else sync_wrapper

    return _timeout

def retry(
        max_count: int = 5,
        interval: int = 2,
        catch_exc: Type[BaseException] = Exception
):
    """
    重试装饰器
    Args:
        max_count: 最大重试次数 默认 5 次
        interval: 每次异常重试间隔 默认 2s
        catch_exc: 指定捕获的异常类用于特定的异常重试 默认捕获 Exception

    Raises:
        MaxRetryException
    """

    def _retry(task_func):

        @functools.wraps(task_func)
        def sync_wrapper(*args, **kwargs):
            # 函数循环重试

            for retry_count in range(max_count):
                logger.info(f"{task_func} execute count {retry_count + 1}")
                try:
                    return task_func(*args, **kwargs)
                except catch_exc:
                    logger.error(f"fail {traceback.print_exc()}")
                    if retry_count < max_count - 1:
                        # 最后一次异常不等待
                        time.sleep(interval)

            # 超过最大重试次数, 抛异常终止
            raise MaxRetryException(f"超过最大重试次数失败, max_retry_count {max_count}")

        @functools.wraps(task_func)
        async def async_wrapper(*args, **kwargs):
            # 异步循环重试
            for retry_count in range(max_count):
                logger.info(f"{task_func} execute count {retry_count + 1}")

                try:
                    return await task_func(*args, **kwargs)
                except catch_exc as e:
                    logger.error(f"fail {str(e)}")
                    if retry_count < max_count - 1:
                        await asyncio.sleep(interval)

            # 超过最大重试次数, 抛异常终止
            raise MaxRetryException(f"超过最大重试次数失败, max_retry_count {max_count}")

        # 异步函数判断
        wrapper_func = async_wrapper if asyncio.iscoroutinefunction(task_func) else sync_wrapper
        return wrapper_func

    return _retry

源代码

---------------------------END---------------------------

题外话

感谢你能看到最后,给大家准备了一些福利!

感兴趣的小伙伴,赠送全套Python学习资料,包含面试题、简历资料等具体看下方。


👉CSDN大礼包🎁:全网最全《Python学习资料》免费赠送🆓!(安全链接,放心点击)

一、Python所有方向的学习路线

Python所有方向的技术点做的整理,形成各个领域的知识点汇总,它的用处就在于,你可以按照下面的知识点去找对应的学习资源,保证自己学得较为全面。

img

二、Python兼职渠道推荐*

学的同时助你创收,每天花1-2小时兼职,轻松稿定生活费.
在这里插入图片描述

三、最新Python学习笔记

当我学到一定基础,有自己的理解能力的时候,会去阅读一些前辈整理的书籍或者手写的笔记资料,这些笔记详细记载了他们对一些技术点的理解,这些理解是比较独到,可以学到不一样的思路。

img

四、实战案例

纸上得来终觉浅,要学会跟着视频一起敲,要动手实操,才能将自己的所学运用到实际当中去,这时候可以搞点实战案例来学习。

img

👉CSDN大礼包🎁:全网最全《Python学习资料》免费赠送🆓!(安全链接,放心点击)

若有侵权,请联系删除

Python重试策略设计:Tenacity实现指数退避与抖动的工程实践 重试机制是分布式系统韧性的基础能力,其本质是应对瞬时故障的自愈策略。原理上需兼顾失败分类、退避调度、状态可观测与下游友好性,技术价值在于避免雪崩、提升SLA并支撑服务降级。典型应用场景包括HTTP外部调用、数据库连接恢复、异步任务重试、消息队列消费、文件锁竞争及gRPC模型推理等。本文聚焦Tenacity库的核心能力——通过声明式配置实现指数退避、随机抖动、精准异常过滤与多维度回调,解决手写while循环导致的重试风暴、固定等待共振、错误误判等高频问题,为Python后端提供生产就绪的重试基础设施。 阅读详情

相关推荐

python中程序超时处理装饰器

如果一个函数处理超时了,需要抛出异常并中止执行,可以使用模块func_timeout中的func_set_timeout做装饰器处理。

LDC,公众号【轻松学编程】 376

Python重试、超时装饰器,手把手教你实现

在写业务代码时候,有许多场景需要重试某块业务逻辑,例如网络请求、购物下单等,希望发生异常的时候多重试几次。本文分享如何利用Python 的装饰器来进行面向切面(AOP)的方式实现自动重试器。

aobulaien001的博客 866

Python 实现失败重试功能的几种方法

在 Python 中实现失败重试功能是处理网络请求、数据库操作等可能因暂时性问题失败的常见需求。本文介绍了五种实现方法:1)手动 while 循环 + 异常捕获,适合简单场景但不够灵活;2)使用 tenacity 库,功能强大且灵活,推荐使用;3)使用 retrying 库,已停止维护,建议用 tenacity 替代;4)requests 自带重试,适用于 HTTP 请求,支持状态码重试和退避策略;5)自定义装饰器,灵活控制重试逻辑。每种方法各有优缺点,开发者可根据具体需求选择合适的方式。

数据知道的博客 1万+

Python超时装饰器:优雅地处理函数执行超时

总的来说,超时装饰器是一个有效的工具,可以帮助我们处理函数执行时间过长的情况,提高程序的稳定性和可靠性。通过合理使用超时装饰器,我们可以有效地提高程序的鲁棒性,确保程序在合理的时间内完成执行。超时装饰器是一种可以应用于函数或方法的装饰器,它的作用是在函数执行时间超过指定时间阈值时抛出异常,从而中断函数的执行。这种装饰器的使用方式使得我们能够更加灵活地控制函数执行的时间,并在超时时进行适当的处理,例如记录日志、发送警报或执行其他必要的操作。需要在保证程序正常执行的前提下,尽量缩短执行时间。

叶子的博客 5240

qupath再度更新:使用WSInfer进行深度学习

我们在下面提供了一个示例,说明如何使用 WSInfer 创建 WSI 中肿瘤和肿瘤浸润淋巴细胞 (TIL) 的空间图谱,这些图谱被认为在几种癌症中既有预后又有预测意义6,10,11,12.由于 WSI 非常大,因此它们通常被分解为补丁,以使分析变得可行。补丁分类的输出通常是空间分类地图,通常可以跨 WSI 集成,以创建表示该幻灯片的诊断、预测或“分数”的单个输出。在当前的实施中,我们专注于斑块分类的通用任务,该任务广泛用于广泛的病理学应用,具有促进诊断、预后或预测功能的深度学习模型。

hx2024的博客 2208

别再死磕USB HID了!用ESP32的Arduino框架手把手教你实现蓝牙鼠标键盘(附完整代码)

本文详细介绍了如何使用ESP32的Arduino框架实现蓝牙HID设备,包括鼠标和键盘的快速开发。通过现成的库和示例代码,开发者可以轻松打造自定义蓝牙外设,无需复杂的USB HID协议栈,适用于演示控制器、宏键盘等多种场景。

weixin_31309419的博客 275

Python的重试装饰器,手把手教你实现它_python 重试装饰器

复制代码复制代码“”"任务重试装饰器Args:max_retry_count: 最大重试次数 默认 5 次time_interval: 每次重试间隔 默认 2smax_timeout: 最大超时时间,单位s 默认为 None,“”"复制代码看看效果。

2401_84584628的博客 1066

别再死记硬背参数了!用ADS手把手教你仿真一个4GHz镜像抑制混频器(附完整工程文件)

本文详细解析了4GHz镜像抑制混频器的ADS仿真全流程,从理论到实践,涵盖混频器设计基础、ADS工程搭建、二极管选型、非线性仿真及性能优化。通过实战案例,帮助工程师掌握关键参数平衡与调试技巧,提升射频电路设计效率。

weixin_42552716的博客 343

Python的重试装饰器,手把手教你实现它

在写业务代码时候,有许多场景需要重试某块业务逻辑,例如网络请求、购物下单等,希望发生异常的时候多重试几次。本文分享如何利用Python 的装饰器来进行面向切面(AOP)的方式实现自动重试器。

Python966的博客 760

华为OD机试双机位C卷:挑选宝石 (C/C++/Python/JAVA/JS/GO)

华为OD机试双机位C卷 挑选宝石,提供C语言、Java、C++、Python、Go、JavaScript源码实现,并提供完整思路讲解。华为OD机试-挑选宝石,华为OD机考-挑选宝石。

qq_45776114的博客 1509

华为OD机试双机位C卷-统计差异值大于相似值二元组个数(C/C++/Py/Java/Js/Go)

华为OD机试(机考)双机位C卷 【统计差异值大于相似值二元组个数】,提供Java、C++、Python、Go、JavaScript源码实现,并提供完整思路讲解,以及在线OJ模拟做题。华为OD机试 - 统计差异值大于相似值二元组个数

qq_45776114的博客 798

2024年Python最新Python的重试装饰器,手把手教你实现它_python 重试装饰器,分享面试经验的软件叫什么

如果你也是看准了Python,想自学Python,在这里为大家准备了丰厚的免费大礼包,带大家一起学习,给大家剖析Python兼职、就业行情前景的这些事儿。

2401_84140776的博客 1067

YOLO26 实战全流程:从数据集标注到端到端无NMS推理(完整版,附ProgLoss核心调参技巧+避坑指南)

本章节是实战经验的精华❌ 数据集标注不规范,导致模型精度低 → ✅ 严格遵守工业级标注规范,标注框紧贴目标边缘,不要漏标/多标;❌ 训练时未使用预训练权重,导致收敛极慢 → ✅ 必须开启,预训练权重能让模型快速收敛;❌ ProgLoss参数调整幅度过大,导致训练崩溃 → ✅ 每次只调整一个参数,幅度±0.02即可,循序渐进;❌ 推理时强行添加NMS参数,画蛇添足 → ✅ YOLO26无需NMS,推理命令中不要加conf/iou参数,否则会降低推理速度;

专注于Python爬虫开发,分享爬虫技巧、项目实战与反爬经验,使用Scrapy、BeautifulSoup等工具,解决数据抓取难题。 1149

Python的重试装饰器,手把手教你实现它_python 重试装饰器(1)

看看效果。

sfdsfgdgd的博客 534

提取边界线的思路与原理

本文提出一种多阶段点云边界提取方法,通过3D→2D→3D的维度转换实现高效处理。首先采用半径滤波去除离群点,将点云投影至二维平面后,运用两级Alpha-Shape算法(α=0.2/1.9)分别提取细节和平滑边界,结合欧式聚类筛选主轮廓。最后通过KD树匹配和体素滤波还原三维边界并去重。实验表明,该方法在保持亚毫米精度的同时,能有效处理建筑等结构化场景,参数设置合理:半径滤波(0.5m/20点)、聚类阈值0.6m、体素尺寸1mm。流程涵盖降噪→投影→边界优化→三维还原全链路,兼顾细节保留与抗噪能力。

weixin_45196569的博客 312

YOLO26改进策略【Neck】| 关键点检测:SDFM 表层细节融合模块,利用通道-空间注意力机制,实现深层与浅层特征融合,抑制噪声干扰

本文记录的是利用SDFM 模块改进 YOLO26 的颈部融合部分,专门用于关键点检测。SDFM模块(Surface Detail Fusion Module,表层细节融合模块) 通过在特征提取网络的浅层引入通道-空间注意力机制,动态生成深层与浅层特征融合权重。该模块可自适应保留不同模态中的独特信息,抑制背景噪声与光照干扰,实现低层细节的精准对齐与互补增强,为后续检测提供高保真度的底层特征表示,从而提升模型在复杂场景下的目标检测鲁棒性与定位准确性。Rethinking the necessity of ima

Limiiiing的博客 193

【Python装饰器进阶实战】:手把手教你实现函数重试退避策略(含5种经典退避算法)

掌握Python装饰器实现函数的重试退避策略,有效应对网络波动与接口超时。涵盖指数退避、随机退避等5种经典算法,适用于API调用、分布式系统等场景,提升程序健壮性与容错能力,代码可复用性强,值得收藏。

AlgoFun的博客 317

温度PID控制PLC程序

温度PID稳定控制程序,适用于欧姆龙PLC,对其他PLC也具有很大参考价值

DeOldify Python调用避坑指南:requests超时/重试/异常捕获最佳实践

本文介绍了如何在星图GPU平台上自动化部署DeOldify图像上色镜像,该镜像基于U-Net深度学习模型实现黑白照片的智能上色。通过平台提供的便捷部署能力,用户可以快速构建稳定的图像处理服务,广泛应用于老照片修复、历史影像还原等场景,提升图像内容的视觉质量。

weixin_42598278的博客 1083

Statistics and Machine Learning Toolbox

Statistics and Machine Learning Toolbox(带书签),MATLAB统计学习工具

大中型超市收银系统(可直接运行)

光步前台收银系统系统功能:商品销售、商品退货、挂单、收银员权限、会员销售、单品取消、整单取消、商品查询、脱机销售、脱机数据上传,基本资料下载,开钱箱、小票打印、收款结算,支持多币种付款方式(现金、储值卡、礼券、微信等),支持多种促销。运行环境:.net 4.0登陆信息用户名:1001 密码:123456内置商品信息,商品编码可输入00001000 - 00010000,测试效果相关功能键F5 结算 F9挂单 F11商品查询 F8退货 Insert单品取消 Del整单取消 F12开钱箱F2 会员 Ctrl+Z退出系统 Home 锁屏 相关源码待公开

Python量化开发:如何给金融行情API写一个优雅的“多线程并发、限流重试”二次封装?

本文介绍如何为量化交易系统封装可靠的金融行情API客户端。针对生产环境中常见的网络抖动、限流和效率问题,提出基于Python的解决方案:1. 使用装饰器实现指数退避重试机制;2. 采用ThreadPoolExecutor实现多线程并发请求;3. 内置频率限制保护。文章详细展示了ReliableQuantClient类的实现代码,包含安全获取K线和实时行情的方法,以及支持批量下载的BatchDataDownloader类。通过实际测试验证了方案的有效性,并提供了线程安全、QPS控制等注意事项。

weixin_45515140的博客 873

文档:亲测可用解决vnc灰屏,黑屏,鼠标大黑叉情况

主要解决vnc-viewer灰屏,黑屏,鼠标大黑叉等现象,详细见文档。

OpenAI API请求超时?别慌,手把手教你配置本地代理(附Python代码示例)

本文详细解析了OpenAI API请求超时(Request timed out)问题的根源与解决方案,提供了从基础排查到高级配置的完整指南。内容包括网络优化、超时设置调整、重试机制实现以及自定义HTTP客户端等实用技巧,并附有Python代码示例,帮助开发者有效解决API连接问题。

weixin_30099989的博客 343

第 4 篇:企业级优化!断言 / 日志 / 异常 / 重试,脚本稳如磐石

本篇聚焦企业级接口自动化脚本优化,解决新手脚本 “不稳定、难排查” 的问题。首先通过 jsonschema 实现多维度精准断言,覆盖状态码、响应格式、业务数据;然后封装企业级日志工具,实现控制台 + 文件双输出,记录请求 / 响应全信息;接着编写全局异常处理装饰器,捕获超时、连接失败等异常,避免脚本崩溃;最后集成失败重试机制,自动重跑偶发失败用例。所有优化点均提供完整可复用代码,同时规范项目目录结构,让脚本从 “能运行” 升级为 “稳运行、易维护”,达到企业落地标准。

weixin_74232595的博客 1247
上一篇: 零基础学习 Python 之错误 & 异常
下一篇: Python新手必读:掌握bytearray对象的使用技巧
Python_P叔
博客等级 码龄3年 5471粉丝 826原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值
⌂ 换网址