httprest 0.1.3__tar.gz → 0.2.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.1
2
2
  Name: httprest
3
- Version: 0.1.3
3
+ Version: 0.2.0
4
4
  Summary: A library for making simple REST-like HTTP requests
5
5
  Home-page: https://github.com/litteratum/httprest
6
6
  License: MIT
@@ -57,7 +57,7 @@ The library exposes an `HTTPClient` interface and provides two implementations f
57
57
  1. `http.urllib_client.UrllibHTTPClient`: the default implementation, uses the `urllib` library under the hood
58
58
  2. `http.requests_client.RequestsHTTPClient`: uses the `requests` library under the hood
59
59
 
60
- You may also define your own HTTP client like this:
60
+ ### Custom HTTP client
61
61
  ```python
62
62
  from httprest.http import HTTPClient, HTTPResponse
63
63
 
@@ -29,7 +29,7 @@ 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
- You may also define your own HTTP client like this:
32
+ ### Custom HTTP client
33
33
  ```python
34
34
  from httprest.http import HTTPClient, HTTPResponse
35
35
 
@@ -56,3 +56,6 @@ class API:
56
56
 
57
57
  def _build_url(self, endpoint: str) -> str:
58
58
  return f"{self._base_url}/{endpoint.strip('/')}"
59
+
60
+ def __str__(self) -> str:
61
+ return f"{self.__class__.__name__}(base_url='{self._base_url}')"
@@ -0,0 +1,8 @@
1
+ """Package for dealing with HTTP."""
2
+
3
+ from .base import HTTPClient, HTTPResponse
4
+
5
+ __all__ = [
6
+ "HTTPClient",
7
+ "HTTPResponse",
8
+ ]
@@ -1,6 +1,5 @@
1
1
  """Base client."""
2
2
 
3
- import json as jsonlib
4
3
  import logging
5
4
  from abc import ABC, abstractmethod
6
5
  from typing import Optional
@@ -8,67 +7,7 @@ from urllib.parse import urlencode
8
7
 
9
8
  from .auth import BaseAuth
10
9
  from .cert import ClientCertificate
11
-
12
-
13
- class HTTPRequestError(Exception):
14
- """Base HTTP request error."""
15
-
16
-
17
- class HTTPConnectionError(HTTPRequestError):
18
- """Any error related to connection."""
19
-
20
-
21
- class HTTPTimeoutError(HTTPRequestError):
22
- """HTTP request timed out."""
23
-
24
-
25
- class HTTPInvalidResponseError(HTTPRequestError):
26
- """HTTP response is invalid."""
27
-
28
-
29
- class HTTPResponse:
30
- """HTTP response wrapper."""
31
-
32
- def __init__(
33
- self, status_code: int, body: Optional[bytes], headers: dict
34
- ) -> None:
35
- self.status_code = status_code
36
- self.body = body or b""
37
- self._headers = headers
38
- self._json = None
39
-
40
- def ok(self) -> bool:
41
- """Return whether the response is successful."""
42
- return self.status_code >= 200 and self.status_code < 400
43
-
44
- @property
45
- def json(self) -> Optional[dict]:
46
- """Return body as JSON."""
47
- if self._json is not None:
48
- return self._json
49
-
50
- headers = {key.lower(): val for key, val in self._headers.items()}
51
- if "application/json" in headers.get("content-type", ""):
52
- try:
53
- self._json = jsonlib.loads(self.body)
54
- except Exception as exc:
55
- raise HTTPInvalidResponseError(
56
- f"Invalid JSON in response: {exc}"
57
- ) from exc
58
-
59
- return self._json
60
-
61
- def __str__(self) -> str:
62
- return f"{self.__class__.__name__}(status={self.status_code})"
63
-
64
- def __repr__(self) -> str:
65
- return (
66
- f"{self.__class__.__name__}("
67
- f"status={self.status_code}, "
68
- f"body={self.body!r}, "
69
- f"headers={self._headers}"
70
- ")"
71
- )
10
+ from .response import HTTPResponse
72
11
 
73
12
 
74
13
  class HTTPClient(ABC):
@@ -0,0 +1,21 @@
1
+ """HTTP errors."""
2
+
3
+
4
+ class HTTPRequestError(Exception):
5
+ """Base HTTP request error."""
6
+
7
+
8
+ class HTTPConnectionError(HTTPRequestError):
9
+ """Any error related to connection."""
10
+
11
+
12
+ class HTTPTimeoutError(HTTPRequestError):
13
+ """HTTP request timed out."""
14
+
15
+
16
+ class HTTPInvalidResponseError(HTTPRequestError):
17
+ """HTTP response is invalid."""
18
+
19
+
20
+ class HTTPError(HTTPRequestError):
21
+ """HTTP error based on the status code."""
@@ -4,7 +4,8 @@ from typing import Any, Dict, List, Optional, Union
4
4
 
5
5
  from httprest.http.base import HTTPResponse
6
6
 
7
- from .base import HTTPClient, HTTPTimeoutError
7
+ from .base import HTTPClient
8
+ from .errors import HTTPTimeoutError
8
9
  from .cert import ClientCertificate
9
10
 
10
11
 
@@ -4,13 +4,9 @@ from typing import Optional
4
4
 
5
5
  import requests
6
6
 
7
- from .base import (
8
- HTTPClient,
9
- HTTPConnectionError,
10
- HTTPRequestError,
11
- HTTPResponse,
12
- HTTPTimeoutError,
13
- )
7
+ from httprest.http import errors as _errors
8
+
9
+ from .base import HTTPClient, HTTPResponse
14
10
  from .cert import ClientCertificate
15
11
 
16
12
 
@@ -48,11 +44,11 @@ class RequestsHTTPClient(HTTPClient):
48
44
  cert=client_cert,
49
45
  )
50
46
  except ConnectionError as exc:
51
- raise HTTPConnectionError(exc) from exc
47
+ raise _errors.HTTPConnectionError(exc) from exc
52
48
  except requests.Timeout as exc:
53
- raise HTTPTimeoutError(exc) from exc
49
+ raise _errors.HTTPTimeoutError(exc) from exc
54
50
  except requests.RequestException as exc:
55
- raise HTTPRequestError(exc) from exc
51
+ raise _errors.HTTPRequestError(exc) from exc
56
52
 
57
53
  return HTTPResponse(
58
54
  response.status_code, response.content, dict(response.headers)
@@ -0,0 +1,59 @@
1
+ """HTTP response."""
2
+
3
+ import json as jsonlib
4
+ from typing import Optional
5
+
6
+ from .errors import HTTPError, HTTPInvalidResponseError
7
+
8
+
9
+ class HTTPResponse:
10
+ """HTTP response wrapper."""
11
+
12
+ def __init__(
13
+ self, status_code: int, body: Optional[bytes], headers: dict
14
+ ) -> None:
15
+ self.status_code = status_code
16
+ self.body = body or b""
17
+ self._headers = headers
18
+ self._json = None
19
+
20
+ @property
21
+ def ok(self) -> bool:
22
+ """Return whether the response is successful."""
23
+ return self.status_code >= 200 and self.status_code < 400
24
+
25
+ def raise_for_status(self) -> None:
26
+ """Raise exception if the response is not successful."""
27
+ if 400 <= self.status_code < 500:
28
+ raise HTTPError(f"Client error {self.status_code}")
29
+ if 500 <= self.status_code < 600:
30
+ raise HTTPError(f"Server error {self.status_code}")
31
+
32
+ @property
33
+ def json(self) -> Optional[dict]:
34
+ """Return body as JSON."""
35
+ if self._json is not None:
36
+ return self._json
37
+
38
+ headers = {key.lower(): val for key, val in self._headers.items()}
39
+ if "application/json" in headers.get("content-type", ""):
40
+ try:
41
+ self._json = jsonlib.loads(self.body)
42
+ except Exception as exc:
43
+ raise HTTPInvalidResponseError(
44
+ f"Invalid JSON in response: {exc}"
45
+ ) from exc
46
+
47
+ return self._json
48
+
49
+ def __str__(self) -> str:
50
+ return f"{self.__class__.__name__}(status={self.status_code})"
51
+
52
+ def __repr__(self) -> str:
53
+ return (
54
+ f"{self.__class__.__name__}("
55
+ f"status={self.status_code}, "
56
+ f"body={self.body!r}, "
57
+ f"headers={self._headers}"
58
+ ")"
59
+ )
@@ -7,13 +7,9 @@ import urllib.parse
7
7
  import urllib.request
8
8
  from typing import Optional
9
9
 
10
- from .base import (
11
- HTTPClient,
12
- HTTPConnectionError,
13
- HTTPRequestError,
14
- HTTPResponse,
15
- HTTPTimeoutError,
16
- )
10
+ from httprest.http import errors as _errors
11
+
12
+ from .base import HTTPClient, HTTPResponse
17
13
  from .cert import ClientCertificate
18
14
 
19
15
 
@@ -50,15 +46,15 @@ class UrllibHTTPClient(HTTPClient):
50
46
  response.status, response.read(), dict(response.headers)
51
47
  )
52
48
  except ConnectionError as exc:
53
- raise HTTPConnectionError(exc) from exc
49
+ raise _errors.HTTPConnectionError(exc) from exc
54
50
  except TimeoutError as exc:
55
- raise HTTPTimeoutError(exc) from exc
51
+ raise _errors.HTTPTimeoutError(exc) from exc
56
52
  except urllib.error.HTTPError as exc:
57
53
  return HTTPResponse(
58
54
  exc.status or 500, exc.read(), dict(exc.headers)
59
55
  )
60
56
  except urllib.error.URLError as exc:
61
- raise HTTPRequestError(exc) from exc
57
+ raise _errors.HTTPRequestError(exc) from exc
62
58
 
63
59
  def __str__(self) -> str:
64
60
  return self.__class__.__name__
@@ -1,6 +1,6 @@
1
1
  [tool.poetry]
2
2
  name = "httprest"
3
- version = "0.1.3"
3
+ version = "0.2.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,17 +0,0 @@
1
- """Package for dealing with HTTP."""
2
-
3
- from .base import (
4
- HTTPClient,
5
- HTTPConnectionError,
6
- HTTPRequestError,
7
- HTTPResponse,
8
- HTTPTimeoutError,
9
- )
10
-
11
- __all__ = [
12
- "HTTPClient",
13
- "HTTPConnectionError",
14
- "HTTPRequestError",
15
- "HTTPResponse",
16
- "HTTPTimeoutError",
17
- ]
File without changes
File without changes
File without changes
File without changes