Advertisement
Guest User

Untitled

a guest
Jun 26th, 2019
78
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.19 KB | None | 0 0
  1. def backoff(test_func, reason=None):
  2. def decorator(func):
  3. @wraps(func)
  4. def inner(*args, **kwargs):
  5. if test_func(*args, **kwargs):
  6. return None
  7.  
  8. result = None
  9. for wait_secs in [0, 1, 4, 9, 16, 32, 64, 128, 256, None]:
  10. result = func(*args, **kwargs)
  11. if test_func(*args, **kwargs):
  12. break
  13.  
  14. if wait_secs is not None:
  15. log.info("Waiting %s seconds.", wait_secs)
  16. time.sleep(wait_secs)
  17. else:
  18. if reason:
  19. raise Exception(reason)
  20. else:
  21. raise Exception('%s failed.' % func)
  22.  
  23. return result
  24. return inner
  25. return decorator
  26.  
  27. def is_authenticated(xyz):
  28. try:
  29. authd = xyz.authenticate() # returns True if successful, otherwise False.
  30. except Exception:
  31. return False # Or, it might raise an Exception.
  32. return authd
  33.  
  34. @backoff(is_authenticated, reason="Cannot Authenticate.")
  35. def do_xyz_things(xyz):
  36. xyz.get('/things')
  37. ...
  38.  
  39. if __name__ == '__main__':
  40. do_xyz_things(XyzApiClient(host))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement