|
| 1 | +import logging |
| 2 | +import requests |
| 3 | + |
| 4 | +from tenacity import ( |
| 5 | + retry, |
| 6 | + retry_if_exception_type, |
| 7 | + stop_after_attempt, |
| 8 | + wait_exponential, |
| 9 | +) |
| 10 | + |
| 11 | + |
| 12 | +logger = logging.getLogger(__name__) |
| 13 | + |
| 14 | + |
| 15 | +class RetryableError(Exception): |
| 16 | + """Recoverable error without having to modify the data state on the client |
| 17 | + side, e.g. timeouts, errors from network partitioning, etc. |
| 18 | + """ |
| 19 | + |
| 20 | + |
| 21 | +class NonRetryableError(Exception): |
| 22 | + """Recoverable error without having to modify the data state on the client |
| 23 | + side, e.g. timeouts, errors from network partitioning, etc. |
| 24 | + """ |
| 25 | + |
| 26 | + |
| 27 | +def _add_param(params, name, value): |
| 28 | + if value: |
| 29 | + params[name] = value |
| 30 | + return params |
| 31 | + |
| 32 | + |
| 33 | +@retry( |
| 34 | + retry=retry_if_exception_type(RetryableError), |
| 35 | + wait=wait_exponential(multiplier=1, min=1, max=5), |
| 36 | + stop=stop_after_attempt(5), |
| 37 | +) |
| 38 | +def post_data( |
| 39 | + url, |
| 40 | + auth=None, |
| 41 | + data=None, |
| 42 | + files=None, |
| 43 | + headers=None, |
| 44 | + json=False, |
| 45 | + timeout=2, |
| 46 | + verify=True, |
| 47 | +): |
| 48 | + """ |
| 49 | + Post data with HTTP |
| 50 | + Retry: Wait 2^x * 1 second between each retry starting with 4 seconds, |
| 51 | + then up to 10 seconds, then 10 seconds afterwards |
| 52 | + Args: |
| 53 | + url: URL address |
| 54 | + files: files |
| 55 | + headers: HTTP headers |
| 56 | + json: True|False |
| 57 | + verify: Verify the SSL. |
| 58 | + Returns: |
| 59 | + Return a requests.response object. |
| 60 | + Except: |
| 61 | + Raise a RetryableError to retry. |
| 62 | + """ |
| 63 | + try: |
| 64 | + params = dict( |
| 65 | + headers=headers, |
| 66 | + timeout=timeout, |
| 67 | + verify=verify, |
| 68 | + ) |
| 69 | + params = _add_param(params, "auth", auth) |
| 70 | + params = _add_param(params, "files", files) |
| 71 | + params = _add_param(params, "data", data) |
| 72 | + response = requests.post(url, **params) |
| 73 | + except (requests.exceptions.ConnectionError, requests.exceptions.Timeout) as exc: |
| 74 | + logger.error("Erro posting data (timeout=%s): %s, retry..., erro: %s" % (timeout, url, exc)) |
| 75 | + raise RetryableError(exc) from exc |
| 76 | + except ( |
| 77 | + requests.exceptions.InvalidSchema, |
| 78 | + requests.exceptions.MissingSchema, |
| 79 | + requests.exceptions.InvalidURL, |
| 80 | + ) as exc: |
| 81 | + raise NonRetryableError(exc) from exc |
| 82 | + try: |
| 83 | + response.raise_for_status() |
| 84 | + except requests.HTTPError as exc: |
| 85 | + if response := is_http_error_json_response(json, response): |
| 86 | + return response |
| 87 | + if 400 <= exc.response.status_code < 500: |
| 88 | + raise NonRetryableError(exc) from exc |
| 89 | + elif 500 <= exc.response.status_code < 600: |
| 90 | + logger.error( |
| 91 | + "Erro fetching the content: %s, retry..., erro: %s" % (url, exc) |
| 92 | + ) |
| 93 | + raise RetryableError(exc) from exc |
| 94 | + else: |
| 95 | + raise |
| 96 | + |
| 97 | + return response.content if not json else response.json() |
| 98 | + |
| 99 | + |
| 100 | +def is_http_error_json_response(json, response): |
| 101 | + """ |
| 102 | + Algumas API, por exemplo, opac_5, retornam a mensagem de erro em formato |
| 103 | + JSON |
| 104 | + """ |
| 105 | + if not json: |
| 106 | + return |
| 107 | + |
| 108 | + try: |
| 109 | + return response.json() |
| 110 | + except Exception as json_error: |
| 111 | + return |
| 112 | + |
| 113 | + |
| 114 | +@retry( |
| 115 | + retry=retry_if_exception_type(RetryableError), |
| 116 | + wait=wait_exponential(multiplier=1, min=1, max=5), |
| 117 | + stop=stop_after_attempt(5), |
| 118 | +) |
| 119 | +def fetch_data(url, params=None, headers=None, json=False, timeout=2, verify=True): |
| 120 | + """ |
| 121 | + Get the resource with HTTP |
| 122 | + Retry: Wait 2^x * 1 second between each retry starting with 4 seconds, |
| 123 | + then up to 10 seconds, then 10 seconds afterwards |
| 124 | + Args: |
| 125 | + url: URL address |
| 126 | + headers: HTTP headers |
| 127 | + json: True|False |
| 128 | + verify: Verify the SSL. |
| 129 | + Returns: |
| 130 | + Return a requests.response object. |
| 131 | + Except: |
| 132 | + Raise a RetryableError to retry. |
| 133 | + """ |
| 134 | + |
| 135 | + try: |
| 136 | + logger.info("Fetching the URL: %s %s" % (url, params)) |
| 137 | + response = requests.get( |
| 138 | + url, params=params, headers=headers, timeout=timeout, verify=verify |
| 139 | + ) |
| 140 | + except (requests.exceptions.ConnectionError, requests.exceptions.Timeout) as exc: |
| 141 | + logger.error("Erro fetching the content: %s, retry..., erro: %s" % (url, exc)) |
| 142 | + raise RetryableError(exc) from exc |
| 143 | + except ( |
| 144 | + requests.exceptions.InvalidSchema, |
| 145 | + requests.exceptions.MissingSchema, |
| 146 | + requests.exceptions.InvalidURL, |
| 147 | + ) as exc: |
| 148 | + raise NonRetryableError(exc) from exc |
| 149 | + try: |
| 150 | + response.raise_for_status() |
| 151 | + except requests.HTTPError as exc: |
| 152 | + if 400 <= exc.response.status_code < 500: |
| 153 | + raise NonRetryableError(exc) from exc |
| 154 | + elif 500 <= exc.response.status_code < 600: |
| 155 | + logger.error( |
| 156 | + "Erro fetching the content: %s, retry..., erro: %s" % (url, exc) |
| 157 | + ) |
| 158 | + raise RetryableError(exc) from exc |
| 159 | + else: |
| 160 | + raise |
| 161 | + |
| 162 | + return response.content if not json else response.json() |
0 commit comments