forked from duboviy/misc
-
Notifications
You must be signed in to change notification settings - Fork 0
/
retry.py
55 lines (43 loc) · 1.61 KB
/
retry.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
51
52
53
54
55
# Helper script with retry utility function
# set logging for `retry` channel
import logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger('retry')
# Define Exception class for retry
class RetryException(Exception):
DESCRIPTION = "Exception ({}) raised after {} tries."
def __init__(self, exception, max_retry):
self.exception = exception
self.max_retry = max_retry
def __unicode__(self):
return self.DESCRIPTION.format(self.exception, self.max_retry)
def __str__(self):
return self.__unicode__()
# Define retry utility function
def retry(func, max_retry=10):
"""
@param func: The function that needs to be retry
(to pass function with arguments use partial object)
@param max_retry: Maximum retry of `func` function, default is `10`
@return: result of func
@raise: RetryException if retries exceeded than max_retry
"""
for retry in range(1, max_retry + 1):
try:
return func()
except Exception, e:
logger.info('Failed to call {}, in retry({}/{})'.format(func.func,
retry, max_retry))
else:
raise RetryException(e, max_retry)
if __name__ == '__main__':
import requests
from functools import partial
def some_request(uri, post):
return requests.post(uri, post)
uri = 'https://site_of_your_friend_you_want_to_disturb.com'
post = {'DDoS_attack': 'true'}
try:
retry_func(partial(some_request, uri, post), max_retry=5)
except RetryException, e:
print(e)