def retry(func):
    """
    Decorator to handle API retries and exceptions. Defaults to three retries.

    Args:
        func (function): function for decoration

    Returns:
        decorated function

    """
    def retried_func(*args, **kwargs):
        max_tries = 3
        tries = 0
        while True:
            try:
                resp = func(*args, **kwargs)

            except requests.exceptions.ConnectionError as exc:
                exc.msg = "Connection error for session; exiting"
                raise exc

            except requests.exceptions.HTTPError as exc:
                exc.msg = "HTTP error for session; exiting"
                raise exc

            if resp.status_code != 200 and tries < max_tries:
                logger.warning("retrying request; current status code: {}"
                               .format(resp.status_code))
                tries += 1
                # mini exponential backoff here.
                time.sleep(tries ** 2)
                continue

            break

        if resp.status_code != 200:
            error_message = resp.json()["error"]["message"]
            logger.error("HTTP Error code: {}: {}".format(resp.status_code, error_message))
            logger.error("Rule payload: {}".format(kwargs["rule_payload"]))
            raise requests.exceptions.HTTPError

        return resp

    return retried_func
def retry ( func ) : def retried_func ( * args , ** kwargs ) : max_tries = 3 tries = 0 while True : try : resp = func ( * args , ** kwargs ) except requests . exceptions . ConnectionError as exc : exc . msg = "Connection error for session; exiting" raise exc except requests . exceptions . HTTPError as exc : exc . msg = "HTTP error for session; exiting" raise exc if resp . status_code != 200 and tries < max_tries : logger . warning ( "retrying request; current status code: {}" . format ( resp . status_code ) ) tries += 1 time . sleep ( tries ** 2 ) continue break if resp . status_code != 200 : error_message = resp . json ( ) [ "error" ] [ "message" ] logger . error ( "HTTP Error code: {}: {}" . format ( resp . status_code , error_message ) ) logger . error ( "Rule payload: {}" . format ( kwargs [ "rule_payload" ] ) ) raise requests . exceptions . HTTPError return resp return retried_func
Decorator to handle API retries and exceptions. Defaults to three retries.

    Args:
        func (function): function for decoration

    Returns:
        decorated function