Skip to content

Commit 45e909e

Browse files
committed
提交代码
1 parent 08d32b3 commit 45e909e

File tree

2 files changed

+92
-0
lines changed

2 files changed

+92
-0
lines changed

xianhuan/README.md

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,8 @@ Python技术 公众号文章代码库
1010

1111
## 实例代码
1212

13+
[Python异常还能写得如此优雅!](https://github.com/JustDoPython/python-examples/tree/master/xianhuan/retry):Python异常还能写得如此优雅!
14+
1315
[神器 Spider!几分钟入门分布式爬虫!](https://github.com/JustDoPython/python-examples/tree/master/xianhuan/disspider):神器 Spider!几分钟入门分布式爬虫!
1416

1517
[神器!五分钟完成大型爬虫项目!](https://github.com/JustDoPython/python-examples/tree/master/xianhuan/airspider):神器!五分钟完成大型爬虫项目!

xianhuan/retry/retryingdemo.py

Lines changed: 90 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,90 @@
1+
#!/usr/bin/env python3
2+
# -*- coding: utf-8 -*-
3+
"""
4+
@author: 闲欢
5+
"""
6+
import random
7+
from retrying import retry
8+
9+
10+
@retry
11+
def do_something_unreliable():
12+
if random.randint(0, 10) > 1:
13+
print("just have a test")
14+
raise IOError("raise exception!")
15+
else:
16+
return "good job!"
17+
18+
19+
print(do_something_unreliable())
20+
21+
22+
# 最大重试次数
23+
@retry(stop_max_attempt_number=5)
24+
def do_something_limited():
25+
print("do something several times")
26+
raise Exception("raise exception")
27+
28+
# do_something_limited()
29+
30+
31+
# 限制最长重试时间(从执行方法开始计算)
32+
@retry(stop_max_delay=5000)
33+
def do_something_in_time():
34+
print("do something in time")
35+
raise Exception("raise exception")
36+
37+
# do_something_in_time()
38+
39+
40+
# 设置固定重试时间
41+
@retry(wait_fixed=2000)
42+
def wait_fixed_time():
43+
print("wait")
44+
raise Exception("raise exception")
45+
46+
# wait_fixed_time()
47+
48+
# 设置重试时间的随机范围
49+
@retry(wait_random_min=1000,wait_random_max=2000)
50+
def wait_random_time():
51+
print("wait")
52+
raise Exception("raise exception")
53+
54+
# wait_random_time()
55+
56+
57+
# 根据异常重试
58+
def retry_if_io_error(exception):
59+
return isinstance(exception, IOError)
60+
61+
# 设置特定异常类型重试
62+
@retry(retry_on_exception=retry_if_io_error)
63+
def retry_special_error():
64+
print("retry io error")
65+
raise IOError("raise exception")
66+
67+
# retry_special_error()
68+
69+
70+
# 通过返回值判断是否重试
71+
def retry_if_result_none(result):
72+
"""Return True if we should retry (in this case when result is None), False otherwise"""
73+
# return result is None
74+
if result =="111":
75+
return True
76+
77+
78+
@retry(retry_on_result=retry_if_result_none)
79+
def might_return_none():
80+
print("Retry forever ignoring Exceptions with no wait if return value is None")
81+
return "111"
82+
83+
might_return_none()
84+
85+
86+
87+
88+
89+
90+

0 commit comments

Comments
 (0)