httprest 0.4.3__tar.gz → 0.5.0__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- {httprest-0.4.3 → httprest-0.5.0}/PKG-INFO +26 -1
- {httprest-0.4.3 → httprest-0.5.0}/README.md +24 -0
- {httprest-0.4.3 → httprest-0.5.0}/httprest/api.py +3 -0
- {httprest-0.4.3 → httprest-0.5.0}/httprest/http/base.py +20 -1
- {httprest-0.4.3 → httprest-0.5.0}/httprest/http/errors.py +8 -0
- {httprest-0.4.3 → httprest-0.5.0}/httprest/http/fake_client.py +5 -1
- httprest-0.5.0/httprest/http/requests_client.py +108 -0
- httprest-0.5.0/httprest/http/timeout.py +18 -0
- {httprest-0.4.3 → httprest-0.5.0}/httprest/http/urllib_client.py +14 -3
- {httprest-0.4.3 → httprest-0.5.0}/pyproject.toml +1 -1
- httprest-0.4.3/httprest/http/requests_client.py +0 -65
- httprest-0.4.3/httprest/http/timeout.py +0 -18
- {httprest-0.4.3 → httprest-0.5.0}/LICENSE +0 -0
- {httprest-0.4.3 → httprest-0.5.0}/httprest/__init__.py +0 -0
- {httprest-0.4.3 → httprest-0.5.0}/httprest/http/__init__.py +0 -0
- {httprest-0.4.3 → httprest-0.5.0}/httprest/http/auth.py +0 -0
- {httprest-0.4.3 → httprest-0.5.0}/httprest/http/cert.py +0 -0
- {httprest-0.4.3 → httprest-0.5.0}/httprest/http/response.py +0 -0
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: httprest
|
|
3
|
-
Version: 0.
|
|
3
|
+
Version: 0.5.0
|
|
4
4
|
Summary: A library for making simple REST-like HTTP requests
|
|
5
5
|
License: MIT
|
|
6
6
|
License-File: LICENSE
|
|
@@ -17,6 +17,7 @@ Classifier: Programming Language :: Python :: 3.11
|
|
|
17
17
|
Classifier: Programming Language :: Python :: 3.12
|
|
18
18
|
Classifier: Programming Language :: Python :: 3.13
|
|
19
19
|
Classifier: Programming Language :: Python :: 3.14
|
|
20
|
+
Classifier: Programming Language :: Python :: 3.15
|
|
20
21
|
Classifier: Programming Language :: Python :: 3 :: Only
|
|
21
22
|
Classifier: Programming Language :: Python :: 3.9
|
|
22
23
|
Classifier: Programming Language :: Python :: Implementation :: CPython
|
|
@@ -58,6 +59,28 @@ The library exposes an `HTTPClient` interface and provides two implementations f
|
|
|
58
59
|
1. `http.urllib_client.UrllibHTTPClient`: the default implementation, uses the `urllib` library under the hood
|
|
59
60
|
2. `http.requests_client.RequestsHTTPClient`: uses the `requests` library under the hood
|
|
60
61
|
|
|
62
|
+
### Timeouts
|
|
63
|
+
A default timeout may be set for the HTTP client and overridden for a single request:
|
|
64
|
+
```python
|
|
65
|
+
from httprest import API
|
|
66
|
+
from httprest.http import Timeout
|
|
67
|
+
from httprest.http.urllib_client import UrllibHTTPClient
|
|
68
|
+
|
|
69
|
+
class MyAPI(API):
|
|
70
|
+
def slow_operation(self):
|
|
71
|
+
# this request only: 60 seconds instead of the default 5
|
|
72
|
+
return self._request("GET", "/slow", timeout=Timeout(read=60))
|
|
73
|
+
|
|
74
|
+
api = MyAPI("http://api.com", http_client=UrllibHTTPClient(Timeout(read=5)))
|
|
75
|
+
```
|
|
76
|
+
|
|
77
|
+
The per-request timeout replaces the default one as a whole: the values are not merged.
|
|
78
|
+
Pass `Timeout()` to perform a request without a timeout.
|
|
79
|
+
|
|
80
|
+
When a request times out, `HTTPConnectTimeoutError` or `HTTPReadTimeoutError` from `http.errors` is raised. Both are subclasses of `HTTPTimeoutError`.
|
|
81
|
+
|
|
82
|
+
**Note**: `urllib` supports a single timeout, so `UrllibHTTPClient` uses the `read` value both for connecting and reading and ignores `connect`.
|
|
83
|
+
|
|
61
84
|
### Custom HTTP client
|
|
62
85
|
```python
|
|
63
86
|
from httprest.http import HTTPClient, HTTPResponse
|
|
@@ -66,6 +89,8 @@ class MyHTTPClient(HTTPClient):
|
|
|
66
89
|
def _request(...) -> HTTPResponse
|
|
67
90
|
```
|
|
68
91
|
|
|
92
|
+
`_request` receives the `timeout` to use for the request: the per-request one or, if it was not provided, the client's default one.
|
|
93
|
+
|
|
69
94
|
And then you simply use it in the API client:
|
|
70
95
|
```python
|
|
71
96
|
|
|
@@ -29,6 +29,28 @@ The library exposes an `HTTPClient` interface and provides two implementations f
|
|
|
29
29
|
1. `http.urllib_client.UrllibHTTPClient`: the default implementation, uses the `urllib` library under the hood
|
|
30
30
|
2. `http.requests_client.RequestsHTTPClient`: uses the `requests` library under the hood
|
|
31
31
|
|
|
32
|
+
### Timeouts
|
|
33
|
+
A default timeout may be set for the HTTP client and overridden for a single request:
|
|
34
|
+
```python
|
|
35
|
+
from httprest import API
|
|
36
|
+
from httprest.http import Timeout
|
|
37
|
+
from httprest.http.urllib_client import UrllibHTTPClient
|
|
38
|
+
|
|
39
|
+
class MyAPI(API):
|
|
40
|
+
def slow_operation(self):
|
|
41
|
+
# this request only: 60 seconds instead of the default 5
|
|
42
|
+
return self._request("GET", "/slow", timeout=Timeout(read=60))
|
|
43
|
+
|
|
44
|
+
api = MyAPI("http://api.com", http_client=UrllibHTTPClient(Timeout(read=5)))
|
|
45
|
+
```
|
|
46
|
+
|
|
47
|
+
The per-request timeout replaces the default one as a whole: the values are not merged.
|
|
48
|
+
Pass `Timeout()` to perform a request without a timeout.
|
|
49
|
+
|
|
50
|
+
When a request times out, `HTTPConnectTimeoutError` or `HTTPReadTimeoutError` from `http.errors` is raised. Both are subclasses of `HTTPTimeoutError`.
|
|
51
|
+
|
|
52
|
+
**Note**: `urllib` supports a single timeout, so `UrllibHTTPClient` uses the `read` value both for connecting and reading and ignores `connect`.
|
|
53
|
+
|
|
32
54
|
### Custom HTTP client
|
|
33
55
|
```python
|
|
34
56
|
from httprest.http import HTTPClient, HTTPResponse
|
|
@@ -37,6 +59,8 @@ class MyHTTPClient(HTTPClient):
|
|
|
37
59
|
def _request(...) -> HTTPResponse
|
|
38
60
|
```
|
|
39
61
|
|
|
62
|
+
`_request` receives the `timeout` to use for the request: the per-request one or, if it was not provided, the client's default one.
|
|
63
|
+
|
|
40
64
|
And then you simply use it in the API client:
|
|
41
65
|
```python
|
|
42
66
|
|
|
@@ -6,6 +6,7 @@ from typing import Union as _Union
|
|
|
6
6
|
|
|
7
7
|
from httprest.http import HTTPClient as _HTTPClient
|
|
8
8
|
from httprest.http import HTTPResponse as _HTTPResponse
|
|
9
|
+
from httprest.http import Timeout as _Timeout
|
|
9
10
|
from httprest.http.auth import BaseAuth as _BaseAuth
|
|
10
11
|
from httprest.http.cert import ClientCertificate as _ClientCertificate
|
|
11
12
|
from httprest.http.urllib_client import UrllibHTTPClient as _UrllibHTTPClient
|
|
@@ -39,6 +40,7 @@ class API:
|
|
|
39
40
|
params: _Optional[dict] = None,
|
|
40
41
|
auth: _Optional[_BaseAuth] = None,
|
|
41
42
|
cert: _Optional[_ClientCertificate] = None,
|
|
43
|
+
timeout: _Optional[_Timeout] = None,
|
|
42
44
|
) -> _HTTPResponse:
|
|
43
45
|
# pylint: disable=too-many-arguments
|
|
44
46
|
"""Make API request.
|
|
@@ -56,6 +58,7 @@ class API:
|
|
|
56
58
|
params=params,
|
|
57
59
|
auth=auth,
|
|
58
60
|
cert=cert,
|
|
61
|
+
timeout=timeout,
|
|
59
62
|
)
|
|
60
63
|
|
|
61
64
|
def _build_url(self, endpoint: _Optional[str]) -> str:
|
|
@@ -15,6 +15,10 @@ class HTTPClient(ABC):
|
|
|
15
15
|
"""Base HTTP client."""
|
|
16
16
|
|
|
17
17
|
def __init__(self, timeout: Optional[Timeout] = None) -> None:
|
|
18
|
+
"""Init client.
|
|
19
|
+
|
|
20
|
+
:param timeout: default timeout. May be overridden per request
|
|
21
|
+
"""
|
|
18
22
|
self._timeout = timeout
|
|
19
23
|
|
|
20
24
|
@abstractmethod
|
|
@@ -26,6 +30,7 @@ class HTTPClient(ABC):
|
|
|
26
30
|
json: Optional[dict] = None,
|
|
27
31
|
headers: Optional[dict] = None,
|
|
28
32
|
cert: Optional[ClientCertificate] = None,
|
|
33
|
+
timeout: Optional[Timeout] = None,
|
|
29
34
|
) -> HTTPResponse:
|
|
30
35
|
# pylint: disable=too-many-arguments
|
|
31
36
|
"""Perform request.
|
|
@@ -35,6 +40,10 @@ class HTTPClient(ABC):
|
|
|
35
40
|
|
|
36
41
|
Headers may be extended if necessary.
|
|
37
42
|
|
|
43
|
+
`timeout` is the timeout to use for this request: the one passed to
|
|
44
|
+
`request` or, if it was not passed, the client's default one. `None`
|
|
45
|
+
means "no timeout".
|
|
46
|
+
|
|
38
47
|
.. warning:: there is no unified handling for `cert`. The client must
|
|
39
48
|
raise NotImplementedError if client side certificates are not
|
|
40
49
|
supported
|
|
@@ -50,6 +59,7 @@ class HTTPClient(ABC):
|
|
|
50
59
|
params: Optional[dict] = None,
|
|
51
60
|
auth: Optional[BaseAuth] = None,
|
|
52
61
|
cert: Optional[ClientCertificate] = None,
|
|
62
|
+
timeout: Optional[Timeout] = None,
|
|
53
63
|
) -> HTTPResponse:
|
|
54
64
|
# pylint: disable=too-many-arguments
|
|
55
65
|
"""Perform HTTP request with a given HTTP method.
|
|
@@ -64,6 +74,9 @@ class HTTPClient(ABC):
|
|
|
64
74
|
:param auth: authorization to use. If provided, the headers will be
|
|
65
75
|
extended
|
|
66
76
|
:param cert: client side certificate
|
|
77
|
+
:param timeout: timeout for this request. If provided, it replaces
|
|
78
|
+
the client's default timeout as a whole (the values are not merged).
|
|
79
|
+
Pass `Timeout()` to perform the request without a timeout
|
|
67
80
|
"""
|
|
68
81
|
logging.info("%s %s", method.upper(), url)
|
|
69
82
|
if auth:
|
|
@@ -71,5 +84,11 @@ class HTTPClient(ABC):
|
|
|
71
84
|
if params:
|
|
72
85
|
url = f"{url}?{urlencode(params)}"
|
|
73
86
|
return self._request(
|
|
74
|
-
method,
|
|
87
|
+
method,
|
|
88
|
+
url,
|
|
89
|
+
data,
|
|
90
|
+
json,
|
|
91
|
+
headers=headers,
|
|
92
|
+
cert=cert,
|
|
93
|
+
timeout=timeout if timeout is not None else self._timeout,
|
|
75
94
|
)
|
|
@@ -13,6 +13,14 @@ class HTTPTimeoutError(HTTPRequestError):
|
|
|
13
13
|
"""HTTP request timed out."""
|
|
14
14
|
|
|
15
15
|
|
|
16
|
+
class HTTPConnectTimeoutError(HTTPTimeoutError):
|
|
17
|
+
"""Timed out while connecting to the server."""
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
class HTTPReadTimeoutError(HTTPTimeoutError):
|
|
21
|
+
"""Timed out while waiting for the server to send data."""
|
|
22
|
+
|
|
23
|
+
|
|
16
24
|
class HTTPInvalidResponseError(HTTPRequestError):
|
|
17
25
|
"""HTTP response is invalid."""
|
|
18
26
|
|
|
@@ -7,6 +7,7 @@ from httprest.http.base import HTTPResponse
|
|
|
7
7
|
from .base import HTTPClient
|
|
8
8
|
from .cert import ClientCertificate
|
|
9
9
|
from .errors import HTTPTimeoutError
|
|
10
|
+
from .timeout import Timeout as _Timeout
|
|
10
11
|
|
|
11
12
|
|
|
12
13
|
class FakeHTTPClient(HTTPClient):
|
|
@@ -15,7 +16,7 @@ class FakeHTTPClient(HTTPClient):
|
|
|
15
16
|
def __init__(
|
|
16
17
|
self, responses: Optional[List[Union[Exception, HTTPResponse]]] = None
|
|
17
18
|
) -> None:
|
|
18
|
-
|
|
19
|
+
super().__init__()
|
|
19
20
|
self.history: List[Dict[str, Optional[Any]]] = []
|
|
20
21
|
self._responses = responses
|
|
21
22
|
|
|
@@ -27,6 +28,7 @@ class FakeHTTPClient(HTTPClient):
|
|
|
27
28
|
json: Optional[dict] = None,
|
|
28
29
|
headers: Optional[dict] = None,
|
|
29
30
|
cert: Optional[ClientCertificate] = None,
|
|
31
|
+
timeout: Optional[_Timeout] = None,
|
|
30
32
|
) -> HTTPResponse:
|
|
31
33
|
# pylint:disable=too-many-arguments
|
|
32
34
|
entry: dict = {
|
|
@@ -43,6 +45,8 @@ class FakeHTTPClient(HTTPClient):
|
|
|
43
45
|
entry["headers"] = headers
|
|
44
46
|
if cert is not None:
|
|
45
47
|
entry["cert"] = cert
|
|
48
|
+
if timeout is not None:
|
|
49
|
+
entry["timeout"] = timeout
|
|
46
50
|
|
|
47
51
|
self.history.append(entry)
|
|
48
52
|
if not self._responses:
|
|
@@ -0,0 +1,108 @@
|
|
|
1
|
+
"""HTTP client which uses `requests` under the hood."""
|
|
2
|
+
|
|
3
|
+
from types import ModuleType
|
|
4
|
+
from typing import Optional, Union
|
|
5
|
+
|
|
6
|
+
import requests
|
|
7
|
+
from urllib3 import exceptions as _urllib3_exceptions
|
|
8
|
+
|
|
9
|
+
from httprest.http import errors as _errors
|
|
10
|
+
|
|
11
|
+
from .base import HTTPClient, HTTPResponse
|
|
12
|
+
from .cert import ClientCertificate
|
|
13
|
+
from .timeout import Timeout
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def _is_read_timeout(exc: requests.ConnectionError) -> bool:
|
|
17
|
+
"""Tell whether the connection error is actually a read timeout.
|
|
18
|
+
|
|
19
|
+
`requests` raises `ReadTimeout` only when the timeout happens while
|
|
20
|
+
waiting for the response. `ConnectionError` wrapping the `urllib3` read
|
|
21
|
+
timeout is raised when it happens:
|
|
22
|
+
|
|
23
|
+
* while reading the response body, or
|
|
24
|
+
* after the retries of a session configured with them are exhausted
|
|
25
|
+
"""
|
|
26
|
+
cause = exc.args[0] if exc.args else None
|
|
27
|
+
if isinstance(cause, _urllib3_exceptions.MaxRetryError):
|
|
28
|
+
cause = cause.reason
|
|
29
|
+
return isinstance(cause, _urllib3_exceptions.ReadTimeoutError)
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
class RequestsHTTPClient(HTTPClient):
|
|
33
|
+
"""`requests` HTTP client.
|
|
34
|
+
|
|
35
|
+
By default a reusable ``requests.Session`` is used (connection reuse).
|
|
36
|
+
Pass ``requester`` to override this:
|
|
37
|
+
|
|
38
|
+
* a custom ``requests.Session`` (e.g. with retries/adapters configured), or
|
|
39
|
+
* the ``requests`` module itself, to make independent module-level calls
|
|
40
|
+
with no connection reuse.
|
|
41
|
+
"""
|
|
42
|
+
|
|
43
|
+
def __init__(
|
|
44
|
+
self,
|
|
45
|
+
timeout: Optional[Timeout] = None,
|
|
46
|
+
requester: Optional[Union[requests.Session, ModuleType]] = None,
|
|
47
|
+
) -> None:
|
|
48
|
+
super().__init__(timeout)
|
|
49
|
+
self._requester = (
|
|
50
|
+
requester if requester is not None else requests.Session()
|
|
51
|
+
)
|
|
52
|
+
|
|
53
|
+
def _request(
|
|
54
|
+
self,
|
|
55
|
+
method: str,
|
|
56
|
+
url: str,
|
|
57
|
+
data: Optional[Union[dict, bytes]] = None,
|
|
58
|
+
json: Optional[dict] = None,
|
|
59
|
+
headers: Optional[dict] = None,
|
|
60
|
+
cert: Optional[ClientCertificate] = None,
|
|
61
|
+
timeout: Optional[Timeout] = None,
|
|
62
|
+
) -> HTTPResponse:
|
|
63
|
+
# pylint: disable=too-many-arguments
|
|
64
|
+
client_cert = None
|
|
65
|
+
if cert:
|
|
66
|
+
client_cert = (
|
|
67
|
+
cert.cert_path
|
|
68
|
+
if cert.key_path is None
|
|
69
|
+
else (cert.cert_path, cert.key_path)
|
|
70
|
+
)
|
|
71
|
+
try:
|
|
72
|
+
response: requests.Response = getattr(
|
|
73
|
+
self._requester, method.lower()
|
|
74
|
+
)(
|
|
75
|
+
url,
|
|
76
|
+
data=data,
|
|
77
|
+
json=json,
|
|
78
|
+
timeout=(
|
|
79
|
+
(timeout.connect, timeout.read)
|
|
80
|
+
if timeout is not None
|
|
81
|
+
else None
|
|
82
|
+
),
|
|
83
|
+
headers=headers,
|
|
84
|
+
cert=client_cert,
|
|
85
|
+
)
|
|
86
|
+
except requests.ConnectTimeout as exc:
|
|
87
|
+
raise _errors.HTTPConnectTimeoutError(exc) from exc
|
|
88
|
+
except requests.ReadTimeout as exc:
|
|
89
|
+
raise _errors.HTTPReadTimeoutError(exc) from exc
|
|
90
|
+
except requests.Timeout as exc:
|
|
91
|
+
raise _errors.HTTPTimeoutError(exc) from exc
|
|
92
|
+
except requests.ConnectionError as exc:
|
|
93
|
+
if _is_read_timeout(exc):
|
|
94
|
+
raise _errors.HTTPReadTimeoutError(exc) from exc
|
|
95
|
+
raise _errors.HTTPConnectionError(exc) from exc
|
|
96
|
+
except ConnectionError as exc:
|
|
97
|
+
# the builtin one: not raised by `requests` itself, but may be
|
|
98
|
+
# raised by a custom transport adapter of the requester
|
|
99
|
+
raise _errors.HTTPConnectionError(exc) from exc
|
|
100
|
+
except requests.RequestException as exc:
|
|
101
|
+
raise _errors.HTTPRequestError(exc) from exc
|
|
102
|
+
|
|
103
|
+
return HTTPResponse(
|
|
104
|
+
response.status_code, response.content, dict(response.headers)
|
|
105
|
+
)
|
|
106
|
+
|
|
107
|
+
def __str__(self) -> str:
|
|
108
|
+
return self.__class__.__name__
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
"""Timeout wrappers."""
|
|
2
|
+
|
|
3
|
+
from dataclasses import dataclass
|
|
4
|
+
from typing import Optional
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
@dataclass(frozen=True)
|
|
8
|
+
class Timeout:
|
|
9
|
+
"""HTTP request timeout.
|
|
10
|
+
|
|
11
|
+
`None` means "no timeout".
|
|
12
|
+
|
|
13
|
+
:param connect: connect timeout in seconds
|
|
14
|
+
:param read: read timeout in seconds
|
|
15
|
+
"""
|
|
16
|
+
|
|
17
|
+
connect: Optional[float] = None
|
|
18
|
+
read: Optional[float] = None
|
|
@@ -11,10 +11,15 @@ from httprest.http import errors as _errors
|
|
|
11
11
|
|
|
12
12
|
from .base import HTTPClient, HTTPResponse
|
|
13
13
|
from .cert import ClientCertificate
|
|
14
|
+
from .timeout import Timeout as _Timeout
|
|
14
15
|
|
|
15
16
|
|
|
16
17
|
class UrllibHTTPClient(HTTPClient):
|
|
17
|
-
"""`urllib` HTTP client.
|
|
18
|
+
"""`urllib` HTTP client.
|
|
19
|
+
|
|
20
|
+
`urllib` supports a single timeout: `Timeout.read` is used both for
|
|
21
|
+
connecting and reading, `Timeout.connect` is ignored.
|
|
22
|
+
"""
|
|
18
23
|
|
|
19
24
|
# pylint: disable=too-many-arguments
|
|
20
25
|
def _request(
|
|
@@ -25,6 +30,7 @@ class UrllibHTTPClient(HTTPClient):
|
|
|
25
30
|
json: Optional[dict] = None,
|
|
26
31
|
headers: Optional[dict] = None,
|
|
27
32
|
cert: Optional[ClientCertificate] = None,
|
|
33
|
+
timeout: Optional[_Timeout] = None,
|
|
28
34
|
) -> HTTPResponse:
|
|
29
35
|
headers = headers or {}
|
|
30
36
|
|
|
@@ -45,7 +51,7 @@ class UrllibHTTPClient(HTTPClient):
|
|
|
45
51
|
headers=headers,
|
|
46
52
|
method=method.upper(),
|
|
47
53
|
),
|
|
48
|
-
timeout=
|
|
54
|
+
timeout=timeout.read if timeout is not None else None,
|
|
49
55
|
) as response:
|
|
50
56
|
return HTTPResponse(
|
|
51
57
|
response.status, response.read(), dict(response.headers)
|
|
@@ -53,12 +59,17 @@ class UrllibHTTPClient(HTTPClient):
|
|
|
53
59
|
except ConnectionError as exc:
|
|
54
60
|
raise _errors.HTTPConnectionError(exc) from exc
|
|
55
61
|
except TimeoutError as exc:
|
|
56
|
-
|
|
62
|
+
# not wrapped by `urllib`: timed out after the request was sent
|
|
63
|
+
raise _errors.HTTPReadTimeoutError(exc) from exc
|
|
57
64
|
except urllib.error.HTTPError as exc:
|
|
58
65
|
return HTTPResponse(
|
|
59
66
|
exc.status or 500, exc.read(), dict(exc.headers)
|
|
60
67
|
)
|
|
61
68
|
except urllib.error.URLError as exc:
|
|
69
|
+
# raised by `urllib` for the errors of connecting to the server
|
|
70
|
+
# and sending the request
|
|
71
|
+
if isinstance(exc.reason, TimeoutError):
|
|
72
|
+
raise _errors.HTTPConnectTimeoutError(exc) from exc
|
|
62
73
|
raise _errors.HTTPRequestError(exc) from exc
|
|
63
74
|
|
|
64
75
|
def __str__(self) -> str:
|
|
@@ -1,65 +0,0 @@
|
|
|
1
|
-
"""HTTP client which uses `requests` under the hood."""
|
|
2
|
-
|
|
3
|
-
from typing import Optional, Union
|
|
4
|
-
|
|
5
|
-
import requests
|
|
6
|
-
|
|
7
|
-
from httprest.http import errors as _errors
|
|
8
|
-
|
|
9
|
-
from .base import HTTPClient, HTTPResponse
|
|
10
|
-
from .cert import ClientCertificate
|
|
11
|
-
from .timeout import Timeout
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
class RequestsHTTPClient(HTTPClient):
|
|
15
|
-
"""`requests` HTTP client."""
|
|
16
|
-
|
|
17
|
-
def __init__(self, timeout: Optional[Timeout] = None) -> None:
|
|
18
|
-
super().__init__(timeout)
|
|
19
|
-
self._session = requests.Session()
|
|
20
|
-
|
|
21
|
-
def _request(
|
|
22
|
-
self,
|
|
23
|
-
method: str,
|
|
24
|
-
url: str,
|
|
25
|
-
data: Optional[Union[dict, bytes]] = None,
|
|
26
|
-
json: Optional[dict] = None,
|
|
27
|
-
headers: Optional[dict] = None,
|
|
28
|
-
cert: Optional[ClientCertificate] = None,
|
|
29
|
-
) -> HTTPResponse:
|
|
30
|
-
# pylint: disable=too-many-arguments
|
|
31
|
-
client_cert = None
|
|
32
|
-
if cert:
|
|
33
|
-
client_cert = (
|
|
34
|
-
cert.cert_path
|
|
35
|
-
if cert.key_path is None
|
|
36
|
-
else (cert.cert_path, cert.key_path)
|
|
37
|
-
)
|
|
38
|
-
try:
|
|
39
|
-
response: requests.Response = getattr(
|
|
40
|
-
self._session, method.lower()
|
|
41
|
-
)(
|
|
42
|
-
url,
|
|
43
|
-
data=data,
|
|
44
|
-
json=json,
|
|
45
|
-
timeout=(
|
|
46
|
-
(self._timeout.connect, self._timeout.read)
|
|
47
|
-
if self._timeout
|
|
48
|
-
else None
|
|
49
|
-
),
|
|
50
|
-
headers=headers,
|
|
51
|
-
cert=client_cert,
|
|
52
|
-
)
|
|
53
|
-
except ConnectionError as exc:
|
|
54
|
-
raise _errors.HTTPConnectionError(exc) from exc
|
|
55
|
-
except requests.Timeout as exc:
|
|
56
|
-
raise _errors.HTTPTimeoutError(exc) from exc
|
|
57
|
-
except requests.RequestException as exc:
|
|
58
|
-
raise _errors.HTTPRequestError(exc) from exc
|
|
59
|
-
|
|
60
|
-
return HTTPResponse(
|
|
61
|
-
response.status_code, response.content, dict(response.headers)
|
|
62
|
-
)
|
|
63
|
-
|
|
64
|
-
def __str__(self) -> str:
|
|
65
|
-
return self.__class__.__name__
|
|
@@ -1,18 +0,0 @@
|
|
|
1
|
-
"""Timeout wrappers."""
|
|
2
|
-
|
|
3
|
-
from typing import Optional
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
class Timeout:
|
|
7
|
-
"""HTTP request timeout."""
|
|
8
|
-
|
|
9
|
-
def __init__(
|
|
10
|
-
self, connect: Optional[float] = None, read: Optional[float] = None
|
|
11
|
-
) -> None:
|
|
12
|
-
"""Init timeout.
|
|
13
|
-
|
|
14
|
-
:param connect: connect timeout in seconds
|
|
15
|
-
:param read: read timeout in seconds
|
|
16
|
-
"""
|
|
17
|
-
self.connect = connect
|
|
18
|
-
self.read = read
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|