Skip to content

Commit

Permalink
Playing with retries.
Browse files Browse the repository at this point in the history
  • Loading branch information
daspecster committed Aug 1, 2016
1 parent bbf5053 commit 067e147
Show file tree
Hide file tree
Showing 2 changed files with 48 additions and 0 deletions.
3 changes: 3 additions & 0 deletions system_tests/bigquery.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@
from gcloud.environment_vars import TESTS_PROJECT
from gcloud import bigquery

from retry import retry
from system_test_utils import unique_resource_id


Expand Down Expand Up @@ -81,6 +82,7 @@ def test_patch_dataset(self):
self.assertEqual(dataset.friendly_name, 'Friendly')
self.assertEqual(dataset.description, 'Description')

@retry(Exception, tries=3, delay=30)
def test_update_dataset(self):
dataset = Config.CLIENT.dataset(DATASET_NAME)
self.assertFalse(dataset.exists())
Expand Down Expand Up @@ -185,6 +187,7 @@ def test_patch_table(self):
self.assertEqual(table.friendly_name, 'Friendly')
self.assertEqual(table.description, 'Description')

@retry(Exception, tries=3, delay=20)
def test_update_table(self):
dataset = Config.CLIENT.dataset(DATASET_NAME)
self.assertFalse(dataset.exists())
Expand Down
45 changes: 45 additions & 0 deletions system_tests/retry.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
import time
from functools import wraps


def retry(ExceptionToCheck, tries=4, delay=3, backoff=2, logger=None):
"""Retry calling the decorated function using an exponential backoff.
http://www.saltycrane.com/blog/2009/11/trying-out-retry-decorator-python/
original from: http://wiki.python.org/moin/PythonDecoratorLibrary#Retry
:param ExceptionToCheck: the exception to check. may be a tuple of
exceptions to check
:type ExceptionToCheck: Exception or tuple
:param tries: number of times to try (not retry) before giving up
:type tries: int
:param delay: initial delay between retries in seconds
:type delay: int
:param backoff: backoff multiplier e.g. value of 2 will double the delay
each retry
:type backoff: int
:param logger: logger to use. If None, print
:type logger: logging.Logger instance
"""
def deco_retry(f):

@wraps(f)
def f_retry(*args, **kwargs):
mtries, mdelay = tries, delay
while mtries > 1:
try:
return f(*args, **kwargs)
except ExceptionToCheck as e:
msg = "%s, Retrying in %d seconds..." % (str(e), mdelay)
if logger:
logger.warning(msg)
else:
print(msg)
time.sleep(mdelay)
mtries -= 1
mdelay *= backoff
return f(*args, **kwargs)

return f_retry # true decorator

return deco_retry

0 comments on commit 067e147

Please sign in to comment.