2021-06-29 20:54:49 +02:00
|
|
|
from typing import Any, Dict, Optional, Union
|
2021-05-07 01:56:31 +02:00
|
|
|
|
|
|
|
import requests
|
2021-06-29 20:54:49 +02:00
|
|
|
from requests.packages.urllib3.util.retry import Retry
|
2021-05-07 01:56:31 +02:00
|
|
|
|
|
|
|
|
|
|
|
class OutgoingSession(requests.Session):
|
2021-06-29 20:54:49 +02:00
|
|
|
def __init__(
|
|
|
|
self,
|
|
|
|
role: str,
|
|
|
|
timeout: int,
|
|
|
|
headers: Optional[Dict[str, str]] = None,
|
|
|
|
max_retries: Optional[Union[int, Retry]] = None,
|
|
|
|
) -> None:
|
2021-05-07 01:56:31 +02:00
|
|
|
super().__init__()
|
2021-06-29 20:54:49 +02:00
|
|
|
retry: Optional[Retry] = Retry(total=0)
|
|
|
|
if max_retries is not None:
|
|
|
|
if isinstance(max_retries, Retry):
|
|
|
|
retry = max_retries
|
|
|
|
else:
|
|
|
|
retry = Retry(total=max_retries, backoff_factor=1)
|
|
|
|
outgoing_adapter = OutgoingHTTPAdapter(role=role, timeout=timeout, max_retries=retry)
|
2021-05-07 01:56:31 +02:00
|
|
|
self.mount("http://", outgoing_adapter)
|
|
|
|
self.mount("https://", outgoing_adapter)
|
2021-05-07 01:57:46 +02:00
|
|
|
if headers:
|
|
|
|
self.headers.update(headers)
|
2021-05-07 01:56:31 +02:00
|
|
|
|
|
|
|
|
|
|
|
class OutgoingHTTPAdapter(requests.adapters.HTTPAdapter):
|
2021-05-07 01:57:30 +02:00
|
|
|
role: str
|
2021-05-07 01:56:31 +02:00
|
|
|
timeout: int
|
|
|
|
|
2021-06-29 20:54:49 +02:00
|
|
|
def __init__(self, role: str, timeout: int, max_retries: Optional[Retry]) -> None:
|
2021-05-07 01:57:30 +02:00
|
|
|
self.role = role
|
2021-05-07 01:56:31 +02:00
|
|
|
self.timeout = timeout
|
2021-06-29 20:54:49 +02:00
|
|
|
super().__init__(max_retries=max_retries)
|
2021-05-07 01:56:31 +02:00
|
|
|
|
2021-08-04 11:18:13 +02:00
|
|
|
def send(self, *args: Any, **kwargs: Any) -> requests.Response:
|
2021-05-07 01:56:31 +02:00
|
|
|
if kwargs.get("timeout") is None:
|
|
|
|
kwargs["timeout"] = self.timeout
|
|
|
|
return super().send(*args, **kwargs)
|
2021-05-07 01:57:30 +02:00
|
|
|
|
|
|
|
def proxy_headers(self, proxy: str) -> Dict[str, str]:
|
|
|
|
return {"X-Smokescreen-Role": self.role}
|