Skip to content

Commit 5242965

Browse files
committed
Add auto retry logic for the sync github client
1 parent 0eb67e5 commit 5242965

2 files changed

Lines changed: 22 additions & 1 deletion

File tree

src/simple_github/client.py

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,8 @@
1313
from gql.transport.requests import RequestsHTTPTransport
1414
from requests import Response as RequestsResponse
1515
from requests import Session
16+
from requests.adapters import HTTPAdapter
17+
from urllib3.util.retry import Retry
1618

1719
if TYPE_CHECKING:
1820
from simple_github.auth import Auth
@@ -132,6 +134,13 @@ def _get_requests_session(self) -> Session:
132134
assert session.transport.session
133135
return session.transport.session
134136

137+
def _get_retry_session(self) -> Session:
138+
session = self._get_requests_session()
139+
retry = Retry(total=5, backoff_factor=1, status_forcelist={500, 502, 503, 504})
140+
adapter = HTTPAdapter(max_retries=retry)
141+
session.mount("https://", adapter)
142+
return session
143+
135144
def request(self, method: str, query: str, **kwargs) -> RequestsResponse:
136145
"""Make a request to Github's REST API.
137146
@@ -145,7 +154,7 @@ def request(self, method: str, query: str, **kwargs) -> RequestsResponse:
145154
Dict: The JSON result of the request.
146155
"""
147156
url = f"{GITHUB_API_ENDPOINT}/{query.lstrip('/')}"
148-
session = self._get_requests_session()
157+
session = self._get_retry_session()
149158

150159
with session.request(method, url, **kwargs) as resp:
151160
return resp

test/test_client.py

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -204,6 +204,18 @@ def test_sync_client_rest(responses, sync_client):
204204
resp.raise_for_status()
205205

206206

207+
def test_sync_client_retries_on_5xx(responses, sync_client):
208+
client = sync_client
209+
url = f"{GITHUB_API_ENDPOINT}/octocat"
210+
211+
responses.get(url, status=502)
212+
responses.get(url, status=200, json={"answer": 42})
213+
214+
resp = client.get("/octocat")
215+
result = resp.json()
216+
assert result == {"answer": 42}
217+
218+
207219
@pytest.mark.asyncio
208220
async def test_async_client_rest_with_text(aioresponses, async_client):
209221
client = async_client

0 commit comments

Comments
 (0)