|
1 | 1 | import logging |
2 | 2 | from typing import Dict |
| 3 | +import urllib3 |
3 | 4 | # pylint: disable=import-error |
4 | 5 | import requests |
5 | 6 | # pylint: disable=import-error |
6 | 7 | from requests.adapters import HTTPAdapter, Retry |
7 | 8 |
|
| 9 | +from bookstack_file_exporter.config_helper.models import HttpConfig |
| 10 | + |
8 | 11 | log = logging.getLogger(__name__) |
9 | 12 |
|
10 | | -def http_get_request(url: str, headers: Dict[str, str], |
11 | | - verify_ssl: bool, timeout: int = 30) -> requests.Response: |
12 | | - """make http requests and return response object""" |
13 | | - url_prefix = should_verify(url) |
14 | | - try: |
15 | | - with requests.Session() as session: |
16 | | - # {backoff factor} * (2 ** ({number of previous retries})) |
17 | | - # {raise_on_status} if status falls in status_forcelist range |
18 | | - # and retries have been exhausted. |
19 | | - # {status_force_list} 413, 429, 503 defaults are overwritten with additional ones |
20 | | - retries = Retry(total=5, |
21 | | - backoff_factor=0.5, |
22 | | - raise_on_status=True, |
23 | | - status_forcelist=[413, 429, 500, 502, 503, 504]) |
24 | | - session.mount(url_prefix, HTTPAdapter(max_retries=retries)) |
25 | | - response = session.get(url, headers=headers, verify=verify_ssl, timeout=timeout) |
26 | | - except Exception as req_err: |
27 | | - log.error("Failed to make request for %s", url) |
28 | | - raise req_err |
29 | | - try: |
30 | | - #raise_for_status() throws an exception on codes 400-599 |
31 | | - response.raise_for_status() |
32 | | - except requests.exceptions.HTTPError as e: |
33 | | - # this means it either exceeded 50X retries in `http_get_request` handler |
34 | | - # or it returned a 40X which is not expected |
35 | | - log.error("Bookstack request failed with status code: %d on url: %s", |
36 | | - response.status_code, url) |
37 | | - raise e |
38 | | - return response |
39 | | - |
40 | | -def should_verify(url: str) -> str: |
41 | | - """check if http or https""" |
42 | | - if url.startswith("https"): |
43 | | - return "https://" |
44 | | - return "http://" |
| 13 | +# disable TLS warnings if using verify_ssl=false |
| 14 | +urllib3.disable_warnings() |
| 15 | + |
| 16 | +class HttpHelper: |
| 17 | + """ |
| 18 | + HttpHelper provides an http request helper with config stored and retries built in |
| 19 | +
|
| 20 | + Args: |
| 21 | + :headers: <Dict[str, str]> = all headers to use for http requests |
| 22 | + :config: <HttpConfig> = Configuration with user inputs for http requests |
| 23 | +
|
| 24 | + Returns: |
| 25 | + :HttpHelper: instance with methods to help with http requests. |
| 26 | + """ |
| 27 | + def __init__(self, headers: Dict[str, str], |
| 28 | + config: HttpConfig): |
| 29 | + self.backoff_factor = config.backoff_factor |
| 30 | + self.retry_codes = config.retry_codes |
| 31 | + self.retry_count = config.retry_count |
| 32 | + self.http_timeout = config.timeout |
| 33 | + self.verify_ssl = config.verify_ssl |
| 34 | + self._headers = headers |
| 35 | + |
| 36 | + # more details on options: https://urllib3.readthedocs.io/en/stable/reference/urllib3.util.html |
| 37 | + def http_get_request(self, url: str) -> requests.Response: |
| 38 | + """make http requests and return response object""" |
| 39 | + url_prefix = self.should_verify(url) |
| 40 | + try: |
| 41 | + with requests.Session() as session: |
| 42 | + # {backoff factor} * (2 ** ({number of previous retries})) |
| 43 | + # {raise_on_status} if status falls in status_forcelist range |
| 44 | + # and retries have been exhausted. |
| 45 | + # {status_force_list} 413, 429, 503 defaults are overwritten with additional ones |
| 46 | + retries = Retry(total=self.retry_count, |
| 47 | + backoff_factor=self.backoff_factor, |
| 48 | + raise_on_status=True, |
| 49 | + status_forcelist=self.retry_codes) |
| 50 | + session.mount(url_prefix, HTTPAdapter(max_retries=retries)) |
| 51 | + response = session.get(url, headers=self._headers, verify=self.verify_ssl, |
| 52 | + timeout=self.http_timeout) |
| 53 | + except Exception as req_err: |
| 54 | + log.error("Failed to make request for %s", url) |
| 55 | + raise req_err |
| 56 | + try: |
| 57 | + #raise_for_status() throws an exception on codes 400-599 |
| 58 | + response.raise_for_status() |
| 59 | + except requests.exceptions.HTTPError as e: |
| 60 | + # this means it either exceeded 50X retries in `http_get_request` handler |
| 61 | + # or it returned a 40X which is not expected |
| 62 | + log.error("Bookstack request failed with status code: %d on url: %s", |
| 63 | + response.status_code, url) |
| 64 | + raise e |
| 65 | + return response |
| 66 | + |
| 67 | + @staticmethod |
| 68 | + def should_verify(url: str) -> str: |
| 69 | + """check if http or https""" |
| 70 | + if url.startswith("https"): |
| 71 | + return "https://" |
| 72 | + return "http://" |
0 commit comments