forked from jackfrued/Python-100-Days
-
Notifications
You must be signed in to change notification settings - Fork 0
/
homework01.py
51 lines (37 loc) · 938 Bytes
/
homework01.py
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
46
47
48
49
50
"""
装饰器的应用
"""
from functools import wraps
from random import randint
from time import sleep
class Retry():
"""让函数可以重试执行的装饰器"""
def __init__(self, times=3, max_wait=0, errors=(Exception, )):
self.times = times
self.max_wait = max_wait
self.errors = errors
def __call__(self, func):
@wraps(func)
def wrapper(*args, **kwargs):
for _ in range(self.times):
try:
return func(*args, **kwargs)
except self.errors:
sleep(randint(self.max_wait))
return wrapper
def retry(*, times=3, max_wait=0, errors=(Exception, )):
"""让函数重试执行的装饰器函数"""
def decorate(func):
@wraps(func)
def wrapper(*args, **kwargs):
for _ in range(times):
try:
return func(*args, **kwargs)
except errors:
sleep(randint(max_wait))
return wrapper
return decorate
# @Retry(max_wait=5)
@retry(max_wait=5)
def get_data_from_url(url):
pass