benym的知识笔记 benym的知识笔记
🦮首页
  • Java

    • Java-基础
    • Java-集合
    • Java-多线程与并发
    • Java-JVM
    • Java-IO
  • Python

    • Python-基础
    • Python-机器学习
  • Kafka
  • Redis
  • MySQL
  • 分布式事务
  • Spring

    • SpringIOC
    • SpringAOP
🦌设计模式
  • 剑指Offer
  • LeetCode
  • 排序算法
🐧实践
  • Rpamis

    • Utils
    • Exception
    • Security
  • 归档
  • 标签
  • 目录
🦉里程碑
🐷关于
GitHub (opens new window)

benym

惟其艰难,才更显勇毅🍂惟其笃行,才弥足珍贵
🦮首页
  • Java

    • Java-基础
    • Java-集合
    • Java-多线程与并发
    • Java-JVM
    • Java-IO
  • Python

    • Python-基础
    • Python-机器学习
  • Kafka
  • Redis
  • MySQL
  • 分布式事务
  • Spring

    • SpringIOC
    • SpringAOP
🦌设计模式
  • 剑指Offer
  • LeetCode
  • 排序算法
🐧实践
  • Rpamis

    • Utils
    • Exception
    • Security
  • 归档
  • 标签
  • 目录
🦉里程碑
🐷关于
GitHub (opens new window)
  • Python-基础

    • assert语句的运用
    • list(列表)、tuple(元组)、dict(字典)的回顾
    • Python中的Docstring
    • Python中的多态
    • Python中的集合
    • Python中的列表
    • Python中的序列以及切片的解释
    • Python中的引用和切片
    • Python中的元组
    • Python中对列表和元组的切片操作
    • Python中完整for循环的实际运用
    • Python中字典(key-value)
    • Python中字符串的一些方法回顾(拆分与合并)
    • Python中字符串的一些方法回顾(切片回顾)
    • Python中字符串的一些方法回顾(文本对齐、去除空白)
    • Python中字符串的一些方法回顾
    • Python中字符串的一些基本操作
    • 多种方法快速交换两个变量的值
    • 利用Python进行文件的自动备份
    • 利用Python进行文件的自动备份(第二版)
    • 利用Python进行文件的自动备份(第三版和第四版)
    • 列表推导
    • 在函数中接受元组与字典
    • 装饰器
      • 代码
      • 运行结果
    • finally异常处理
    • Python的__name__ = '__main__' 的作用
    • Python的pickle模块
    • Python对象的实例化
    • Python日志模块
    • Python中的__new__方法的重写
    • Python中的lambda函数
    • Python中的静态方法、实例方法、类方法的区别
    • Python中的正则表达式
    • Python中的正则表达式match和search
    • Python中面向对象比较简单的内部函数
    • with open异常处理
    • 单例设计模式
    • 继承的运用
    • 简单的异常处理
    • 类变量与对象变量
    • 输入输出——简单的回文判断
    • 输入输出——回文字串的判断(加强版)
    • 文件操作
    • 用户自己引发的异常处理
    • 正则表达式检索与替换
    • 正则表达式中的compile函数
    • 正则表达式中的compile函数(二)
  • Python-机器学习

    • Numpy库的首次使用
    • kNN(k-近邻算法)
    • kNN识别手写图像
    • LogisticRegression(逻辑回归)
    • Ndarray对象
    • Numpy中的数组维度
    • Numpy中花式索引和shape用法
    • turtle绘图库
    • 第一个使用Tensorflow的程序
    • 将下载下来的MNIST手写数字数据集转化成为图片
    • Tensorflow交互式使用
    • 使用k-近邻算法改进约会网站的配对效果
    • Numpy数据类型和arange方法、astype方法的使用
    • 一些TensorFlow的基本操作
  • Python
  • Python-基础
benym
2018-07-24
目录

装饰器

# 装饰器

装饰器(Decorators)是应用包装函数的快捷方式。这有助于将某一功能与一些代码一遍又一 遍地“包装”。举个例子,我为自己创建了一个 retry 装饰器,这样我可以将其运用到任何函 数之中,如果在一次运行中抛出了任何错误,它就会尝试重新运行,直到最大次数 5 次,并 且每次运行期间都会有一定的延迟。这对于你在对一台远程计算机进行网络调用的情况十分 有用:

# 代码

# 从time模块引入sleep函数
from time import sleep
from functools import wraps
import logging

logging.basicConfig()
log = logging.getLogger("retry")


def retry(f):
    @wraps(f)
    def wrapped_f(*args, **kwargs):
        MAX_ATTEMPTS = 5
        for attempt in range(1, MAX_ATTEMPTS + 1):
            try:
                return f(*args, **kwargs)
            except:
                log.exception("Attempt %s %s failed : %s",
                              attempt, MAX_ATTEMPTS, (args, kwargs))
                sleep(10 * attempt)
        log.critical("All %s attempts failed : %s",
                     MAX_ATTEMPTS,
                     (args, kwargs))

    return wrapped_f


counter = 0


@retry
def save_to_database(arg):
    print("Write to a database or make a network call or etc.")
    print("This will be automatically retried if exception is thrown.")
    global counter
    counter += 1
    # 这将在第一次调用时抛出异常
    # 在第二次运行时正常工作(也就是重试)
    if counter < 2:
        raise ValueError(arg)


# 让你写的脚本模块既可以导入到别的模块中用,另外该模块自己也可执行。
if __name__ == '__main__':
    save_to_database("Some bad value")
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45

# 运行结果

ERROR:retry:Attempt 1 5 failed : (('Some bad value',), {})
Traceback (most recent call last):
  File "E:/PythonProject/more/more_decorators.py", line 16, in wrapped_f
    return f(*args, **kwargs)
  File "E:/PythonProject/more/more_decorators.py", line 40, in save_to_database
    raise ValueError(arg)
ValueError: Some bad value
Write to a database or make a network call or etc.
This will be automatically retried if exception is thrown.
Write to a database or make a network call or etc.
This will be automatically retried if exception is thrown.
1
2
3
4
5
6
7
8
9
10
11
1
2
3
4
5
6
7
8
9
10
11
编辑 (opens new window)
#Python基础
上次更新: 2022/12/31, 16:52:27
在函数中接受元组与字典
finally异常处理

← 在函数中接受元组与字典 finally异常处理→

最近更新
01
SpringCache基本配置类
05-16
02
DSTransactional与Transactional事务混用死锁场景分析
03-04
03
Rpamis-security-原理解析
12-13
更多文章>
Theme by Vdoing | Copyright © 2018-2024 benym | MIT License
 |   |   | 
渝ICP备18012574号 | 渝公网安备50010902502537号
  • 跟随系统
  • 浅色模式
  • 深色模式
  • 阅读模式