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

python装饰器---重试 在工作当中会碰到出现异常情况进行重试的情况,比如我们要保持一个页面的心跳时,由于等待时长原因导致页面失效时报错,这种情况下我们需要进行重新进行刷新页面、点击某个页面元素等进行维持页面心跳。我们可以用重试装饰器来进行几次尝试操作。 直接上代码: import time import functools def retry(exceptions: list, times=3, wait=1): """ 如果抛出指定异常,重试 :param exceptions: 异常列表 阅读详情

一、前言

在写业务代码时候,有许多场景需要重试某块业务逻辑,例如网络请求、购物下单等,希望发生异常的时候多重试几次。本文分享如何利用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
复制代码

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

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

作者:忆想不到的晖
链接:Python重试装饰器,手把手教你实现 - 掘金
来源:稀土掘金
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

 

异常重试装饰器进阶:在重试前增加回调方法,轻松切换代理 在上一篇《日常避坑指南:重试装饰器的正确使用方式》中,我们详细讲解了如何使用简单的重试装饰器来处理常见的异常。虽然这种装饰器能自动捕捉异常并进行重试,但它并没有提供执行额外操作的灵活性。比如,如果你在做爬虫开发,可能需要在每次重试前更换代理,或者清理某些状态,这种情况下,简单的重试逻辑就显得不够用了。为了解决这个问题,我们可以在重试装饰器中增加一个“重试前回调函数”。通过这个回调函数,我们可以在每次重试之前执行自定义的操作,例如切换代理、清除缓存等。接下来,我们就来看看具体的实现。 阅读详情

相关推荐

从requests请求重试到万能重试装饰器

从requests请求重试到万能重试装饰器 重试,在编写代码的过程中,是一个很常见的需求。 比如: 请求重试(例如:超时) 文件占用 IO阻塞等待 那么,我们如何编写重试的代码呢? 本文将从请求重试开始,带大家从简单的超时重试,最后编写到万能错误重试。 主要涉及内容: requests adapter 函数装饰器 类装饰器 话不多说,start! 因为我们需要从 requests 请求...

dustyposa的博客 1282

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

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

2401_87368838的博客 1122

Cocos Creator Android打包:NDK版本选择与配置全攻略

在Android原生开发中,NDK(Native Development Kit)是编译C/C++代码的核心工具链,它决定了代码如何被编译为不同CPU架构(如ARMv7、ARM64)的动态库。其工作原理在于提供了一套完整的交叉编译环境,将高级语言代码转化为设备可执行的二进制指令。这一技术对于游戏引擎和性能敏感型应用至关重要,因为它能直接调用硬件资源,提升运行效率。在实际工程中,NDK版本必须与Android Gradle插件(AGP)版本、项目依赖的C++标准库精密匹配,否则会导致编译失败或运行时崩溃。特别

weixin_33725270的博客 491

【python 装饰器 - 重试】做一个简易重试装饰器,如果函数执行错误则会自动重新执行,可设置重试次数,对爬虫比较友好

当出现错误的时候,会自动重试。 [retry]:默认为重试3次,可设置

₰₯₮ 的博客 795

手推反向传播+numpy实现

反向传播的重要性不必多说,手推也是必备基础,大厂面试要求用numpy实现一下BP也是经常的事。下面以一个简单的两层网络为例(简单到连bias都没有的那种),真·手推反向传播+numpy实现。 说明: input:输入 net_h:隐层 S(x):sigmoid简写 SD(x):sigmoid导数的简写 out_h:隐层经过sigmoid激活的输出 net_o:输出层 out_o:经过经过sigmoid激活的输出层,也就是最后的输出 target(简写t1、t2):Ground...

xian0710830114的专栏 1238

在Ubuntu 22.04上从零搭建TrinityCore 3.3.5服务器:一份保姆级避坑指南

本文详细介绍了在Ubuntu 22.04系统上从零搭建TrinityCore 3.3.5服务器的完整流程,包括环境准备、源码编译、数据库配置、资源文件处理及性能调优等关键步骤。特别针对国内开发者和低配置用户优化,提供保姆级避坑指南,帮助用户高效搭建魔兽世界经典旧世版本私服。

weixin_33393017的博客 304

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

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

Saki_Python的博客 755

电子科技大学计算机预推免(最终去向)

电子科技大学,预推免报名时必须要有一封本校老师写的推荐信,推荐信基本上就是复试的入场券,所以一定要提前联系老师,拿到推荐信。只要有机会进了面试,我觉得老师对于双非并不歧视,面试的个人表现才是关键性决定因素,技巧性也是很强的,如果有需要帮助的,欢迎私信~~

D1379951481的博客 3368

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

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

Saki_Python的博客 1319

BLDC&PMSM电机控制器硬件设计工程(八)72V 10kW电机控制器原理图工程及库文件

电机控制器基本需求:接口类型;MCU平台;通信接口;供电;信号采集;信号输出;功率;EMC或者认证需求。

小幽余生不加糖 375

56、Cortex - M33处理器浮点单元(FPU)的使用与优化

本文详细介绍了Cortex-M33处理器浮点单元(FPU)的使用与优化方法,涵盖单双精度浮点计算的选择、编译器命令行配置、ABI模式对比、特殊FPU模式设置(如Flush-to-Zero、Default NaN)、浮点异常处理机制以及FPU电源管理策略。结合代码示例和流程图,提供了在不同应用场景下的最佳实践建议,并总结了常见问题及解决方案,帮助开发者提升嵌入式系统中浮点运算的性能、精度与能效。

bread的博客 155

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

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

2401_84140776的博客 1067

【异常】XXL-JOB提示异常ERROR com.xxl.job.core.util.XxlJobRemotingUtil - connect timed out

打开XXL-JOB的ELK,发现一堆报错。

奶爸的编程之路,也就一周冷个三天 2049

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

看看效果。

sfdsfgdgd的博客 533

uni-app - 将 base64 图片编码转为 Blob 本地文件路径(把base64类型的图片,转换成blob二进制文件流)适用于 uni-app / vue.js / JavaScript

uni-app/vue.js/JavaScript将base64转Blob,uniappapp端如何将图片的base64编码转换成File对象或Blob,uni-app/vue.js/JavaScript中拿到base64转blob对象,uniapp图片base64格式转blob格式方法,uniapp上传图片压缩转base64码与base64转图片路径,Base64/Blob/File图片文件转换,url、base64、blob相互转换方法,读取本地文件为Base64并转成B

🏆 前端领域优质创作者 1万+

VB摄像头监控

该VB模块可对摄像头捕获的画面进行录像等,可在创建的窗口进行控制

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

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

AlgoFun的博客 317

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

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

Python中利用装饰器优雅地实现函数重试机制

重试机制的核心逻辑是当某个函数执行失败时,不是立即抛出异常,而是等待一段时间后再次尝试执行,如此重复直到成功或达到预设的重试次数上限。为了提高程序的健壮性,实现重试机制是一种常见的策略。Python中的装饰器以其优雅的语法和强大的功能,为实现函数重试提供了极为便利的方式。除了自定义实现外,Python社区也提供了一些成熟的重试库,如`tenacity`库,它提供了更为丰富和灵活的重试策略。这个版本的装饰器增加了退避因子参数,每次重试的等待时间都会是前一次的两倍(或其他指定倍数),从而实现了指数退避。

ZefCaEAU的博客 1511

Devexpress16.2.6破解工具

Devexpress16.2.6破解工具Devexpress16.2.6破解工具Devexpress16.2.6破解工具Devexpress16.2.6破解工具

Probability and Statistics - 4th edition

Probability and Statistics - 4th edition

Python:从requests请求重试到万能重试装饰器

今天来介绍下Python中从requests请求重试到万能重试装饰器。 从requests请求重试到万能重试装饰器 重试,在编写代码的过程中,是一个很常见的需求。 比如: 请求重试(例如:超时) 文件占用 IO阻塞等待 那么,我们如何编写重试的代码呢? 本文将从请求重试开始,带大家从简单的超时重试,最后编写到万能错误重试。 主要涉及内容: requests adapter 函数装饰器 类装饰...

python学习者的博客 3998

Python装饰器实战:实现优雅的重试机制

重试机制在编程中是比较常见的场景,主要被用于处理那些可能由于临时性故障或网络波动等原因而失败的操作。

DEVELOPERAA的博客 1367

如何用Python装饰器函数实现重试策略

实现重试装饰器可以防止意外的异常。 人们通常将Python描述为“胶水语言”。在我看来,“胶水”意味着一种语言能够连接系统,确保数据以正确的格式从A点达到B点。 我用Python构建了无数的ETL脚本(Extract, Transform, Load)。所有这些脚本基本上都按照相同的原理运行,从某处提取数据,转换数据,然后运行最终操作。最后的操作通常意味着将数据上传到某个地方。 现代科技公司的基础架构中越来越多的一部分正在迁移到云中,这意味着您可能需要从某个地方提取数据或在非本地计算机上写入数据。 当处理的

量化炼金 | CodeAlchemy 663
上一篇: 为什么越来越多的人开始想要学python?
下一篇: Python基础篇:Python基础知识,帮助初学者快速入门
AI大模型学习
博客等级 码龄4年 2475粉丝 620原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值