Skip to content

Commit cb0f31d

Browse files
authored
Merge pull request #18 from evrone/feature/exceptions
handle too many requests response error
2 parents f9337c5 + 64e50c9 commit cb0f31d

File tree

3 files changed

+41
-6
lines changed

3 files changed

+41
-6
lines changed

tests/test_api.py

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
from unittest import mock
2+
3+
import httpx
4+
import pytest
5+
6+
from toggl_python import ReportTimeEntries, TokenAuth
7+
from toggl_python.exceptions import TooManyRequests
8+
9+
10+
def test_raises_too_many_requests():
11+
auth = TokenAuth("token")
12+
report_time_entries_api = ReportTimeEntries(auth=auth)
13+
with mock.patch.object(
14+
report_time_entries_api.client,
15+
"get",
16+
mock.MagicMock(__name__="get", return_value=httpx.Response(status_code=429, text="test")),
17+
):
18+
with pytest.raises(TooManyRequests):
19+
report_time_entries_api.list()

toggl_python/api.py

Lines changed: 5 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@
77
import httpx
88

99
from .auth import BasicAuth, TokenAuth
10-
from .exceptions import STATUS_2_EXCEPTION
10+
from .exceptions import raise_from_response
1111

1212

1313
class Api:
@@ -78,8 +78,7 @@ def api_method(
7878
headers=self.HEADERS,
7979
)
8080
)
81-
if response.status_code == httpx.codes.OK:
82-
return response
83-
else:
84-
exception_class = STATUS_2_EXCEPTION[response.status_code]
85-
raise exception_class(response.text)
81+
82+
raise_from_response(response)
83+
84+
return response

toggl_python/exceptions.py

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,6 @@
1+
import httpx
2+
3+
14
class TogglException(Exception):
25
pass
36

@@ -26,10 +29,24 @@ class NotSupported(TogglException):
2629
pass
2730

2831

32+
class TooManyRequests(TogglException):
33+
pass
34+
35+
2936
STATUS_2_EXCEPTION = {
3037
400: BadRequest,
3138
401: Unauthorized,
3239
403: Forbidden,
3340
404: NotFound,
3441
405: MethodNotAllowed,
42+
429: TooManyRequests,
3543
}
44+
45+
46+
def raise_from_response(response: httpx.Response) -> None:
47+
"""Raise exception based on the response status code."""
48+
if response.status_code < 400:
49+
return
50+
51+
exception_cls = STATUS_2_EXCEPTION.get(response.status_code, TogglException)
52+
raise exception_cls(response.text)

0 commit comments

Comments
 (0)