httprest 0.4.4__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.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: httprest
3
- Version: 0.4.4
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, url, data, json, headers=headers, cert=cert
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
- # pylint:disable=super-init-not-called
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:
@@ -4,6 +4,7 @@ from types import ModuleType
4
4
  from typing import Optional, Union
5
5
 
6
6
  import requests
7
+ from urllib3 import exceptions as _urllib3_exceptions
7
8
 
8
9
  from httprest.http import errors as _errors
9
10
 
@@ -12,6 +13,22 @@ from .cert import ClientCertificate
12
13
  from .timeout import Timeout
13
14
 
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
+
15
32
  class RequestsHTTPClient(HTTPClient):
16
33
  """`requests` HTTP client.
17
34
 
@@ -41,6 +58,7 @@ class RequestsHTTPClient(HTTPClient):
41
58
  json: Optional[dict] = None,
42
59
  headers: Optional[dict] = None,
43
60
  cert: Optional[ClientCertificate] = None,
61
+ timeout: Optional[Timeout] = None,
44
62
  ) -> HTTPResponse:
45
63
  # pylint: disable=too-many-arguments
46
64
  client_cert = None
@@ -58,17 +76,27 @@ class RequestsHTTPClient(HTTPClient):
58
76
  data=data,
59
77
  json=json,
60
78
  timeout=(
61
- (self._timeout.connect, self._timeout.read)
62
- if self._timeout
79
+ (timeout.connect, timeout.read)
80
+ if timeout is not None
63
81
  else None
64
82
  ),
65
83
  headers=headers,
66
84
  cert=client_cert,
67
85
  )
68
- except ConnectionError as exc:
69
- raise _errors.HTTPConnectionError(exc) from exc
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
70
90
  except requests.Timeout as exc:
71
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
72
100
  except requests.RequestException as exc:
73
101
  raise _errors.HTTPRequestError(exc) from exc
74
102
 
@@ -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=self._timeout.read if self._timeout else None,
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
- raise _errors.HTTPTimeoutError(exc) from exc
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,6 +1,6 @@
1
1
  [tool.poetry]
2
2
  name = "httprest"
3
- version = "0.4.4"
3
+ version = "0.5.0"
4
4
  description = "A library for making simple REST-like HTTP requests"
5
5
  authors = ["Andrii Nechaiev <andrewnech@gmail.com>"]
6
6
  readme = "README.md"
@@ -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