|
| 1 | +import requests |
| 2 | +import time |
| 3 | +import random |
| 4 | +from requests.exceptions import JSONDecodeError |
| 5 | +from .problem import ProblemDecoder, LegacyProblemDecoder, LegacyProblem, Problem |
| 6 | + |
| 7 | +MAX_RETRIES = 3 |
| 8 | +RETRY_BACKOFF_FACTOR = 1.0 |
| 9 | +RETRY_BACKOFF_JITTER = 3.0 |
| 10 | +RETRY_BACKOFF_MAX = 30.0 |
| 11 | + |
| 12 | + |
| 13 | +class Retry: |
| 14 | + """ |
| 15 | + Hold a request attempt and try to execute it |
| 16 | + """ |
| 17 | + |
| 18 | + def __init__(self, session: requests.Session, method: str, url: str, **kwargs): |
| 19 | + self.session = session |
| 20 | + self.method: str = method |
| 21 | + self.url: str = url |
| 22 | + self.request_kwargs = kwargs |
| 23 | + |
| 24 | + # Extract all retry parameters |
| 25 | + self.attempt: int = int(self.request_kwargs.pop("attempt", 0)) |
| 26 | + self.max_retries: float = int( |
| 27 | + self.request_kwargs.get("max_retries", MAX_RETRIES) |
| 28 | + ) |
| 29 | + self.backoff_factor: float = float( |
| 30 | + self.request_kwargs.get("backoff_factor", RETRY_BACKOFF_FACTOR) |
| 31 | + ) |
| 32 | + self.backoff_jitter: float = float( |
| 33 | + self.request_kwargs.get("backoff_jitter", RETRY_BACKOFF_JITTER) |
| 34 | + ) |
| 35 | + self.backoff_max: float = float( |
| 36 | + self.request_kwargs.get("backoff_max", RETRY_BACKOFF_MAX) |
| 37 | + ) |
| 38 | + |
| 39 | + def execute_once(self) -> requests.Response: |
| 40 | + """ |
| 41 | + Execute the request without retry |
| 42 | + """ |
| 43 | + return self.session.request(self.method, self.url, **self.request_kwargs) |
| 44 | + |
| 45 | + def increment(self) -> "Retry": |
| 46 | + """ |
| 47 | + Return a copy of the retry with an incremented attempt count |
| 48 | + """ |
| 49 | + new_kwargs = self.request_kwargs.copy() |
| 50 | + new_kwargs["attempt"] = self.attempt + 1 |
| 51 | + return Retry(self.session, self.method, self.url, **new_kwargs) |
| 52 | + |
| 53 | + def should_retry(self, e: requests.exceptions.RequestException) -> bool: |
| 54 | + if isinstance(e, requests.exceptions.TooManyRedirects): |
| 55 | + return False |
| 56 | + |
| 57 | + if isinstance(e, requests.exceptions.URLRequired): |
| 58 | + return False |
| 59 | + |
| 60 | + if isinstance(e, ValueError): |
| 61 | + # can be raised on bogus request |
| 62 | + return False |
| 63 | + |
| 64 | + if e.response is not None: |
| 65 | + if 400 <= e.response.status_code < 500 and e.response.status_code != 429: |
| 66 | + return False |
| 67 | + |
| 68 | + return self.attempt < self.max_retries |
| 69 | + |
| 70 | + def get_backoff_time(self) -> float: |
| 71 | + """ |
| 72 | + {backoff factor} * (2 ** ({number of previous retries})) |
| 73 | + random.uniform(0, {backoff jitter}) |
| 74 | + """ |
| 75 | + |
| 76 | + backoff: float = self.backoff_factor * (2**self.attempt) |
| 77 | + backoff += random.uniform(0, self.backoff_jitter) |
| 78 | + return min(backoff, self.backoff_max) |
| 79 | + |
| 80 | + def execute(self) -> requests.Response: |
| 81 | + try: |
| 82 | + res = self.execute_once() |
| 83 | + raise_for_status(res) |
| 84 | + return res |
| 85 | + except requests.exceptions.RequestException as e: |
| 86 | + if self.should_retry(e): |
| 87 | + sleep_time = self.get_backoff_time() |
| 88 | + time.sleep(sleep_time) |
| 89 | + return self.increment().execute() |
| 90 | + else: |
| 91 | + raise e |
| 92 | + |
| 93 | + |
| 94 | +def raise_for_status(response: requests.Response): |
| 95 | + http_error_msg = "" |
| 96 | + problem = None |
| 97 | + reason = get_default_reason(response) |
| 98 | + |
| 99 | + try: |
| 100 | + ct = response.headers.get("content-type") or "" |
| 101 | + if "application/json" in ct: |
| 102 | + problem = response.json(cls=LegacyProblemDecoder) |
| 103 | + problem.status = problem.status or str(response.status_code) |
| 104 | + problem.url = response.url |
| 105 | + elif "application/problem+json" in ct: |
| 106 | + problem = response.json(cls=ProblemDecoder) |
| 107 | + problem.status = problem.status or str(response.status_code) |
| 108 | + except JSONDecodeError: |
| 109 | + pass |
| 110 | + else: |
| 111 | + if 400 <= response.status_code < 500: |
| 112 | + if isinstance(problem, LegacyProblem) or isinstance(problem, Problem): |
| 113 | + http_error_msg = f"Client Error --> {problem.msg()}" |
| 114 | + else: |
| 115 | + http_error_msg = f"{response.status_code} Client Error: {reason} for url: {response.url}" |
| 116 | + |
| 117 | + elif 500 <= response.status_code < 600: |
| 118 | + if isinstance(problem, LegacyProblem) or isinstance(problem, Problem): |
| 119 | + http_error_msg = f"Server Error --> {problem.msg()}" |
| 120 | + else: |
| 121 | + http_error_msg = f"{response.status_code} Server Error: {reason} for url: {response.url}" |
| 122 | + |
| 123 | + if http_error_msg: |
| 124 | + raise requests.HTTPError(http_error_msg, response=response) |
| 125 | + |
| 126 | + |
| 127 | +def get_default_reason(response): |
| 128 | + if isinstance(response.reason, bytes): |
| 129 | + # We attempt to decode utf-8 first because some servers |
| 130 | + # choose to localize their reason strings. If the string |
| 131 | + # isn't utf-8, we fall back to iso-8859-1 for all other |
| 132 | + # encodings. (See PR #3538) |
| 133 | + try: |
| 134 | + return response.reason.decode("utf-8") |
| 135 | + except UnicodeDecodeError: |
| 136 | + return response.reason.decode("iso-8859-1") |
| 137 | + else: |
| 138 | + return response.reason |
0 commit comments