Skip to content

Commit c0ecae5

Browse files
ariarijpsmaeda-ks
authored andcommitted
Add timeout option to Request class for better error handling. (#234)
* Add timeout option to Request class for better error handling. * Adding retry_on_timeouts option
1 parent f67a493 commit c0ecae5

File tree

2 files changed

+21
-4
lines changed

2 files changed

+21
-4
lines changed

tests/test_client.py

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -59,10 +59,11 @@ def test_accounts_with_options():
5959
'handle_rate_limit': True,
6060
'retry_max': 1,
6161
'retry_delay': 3000,
62-
'retry_on_status': [404, 500, 503]
62+
'retry_on_status': [404, 500, 503],
63+
'timeout': (1.0, 3.0)
6364
}
6465
)
6566

6667
assert client is not None
6768
assert isinstance(client, Client)
68-
assert len(client.options) == 4
69+
assert len(client.options) == 5

twitter_ads/http.py

Lines changed: 18 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@
1515
else:
1616
import http.client as httplib
1717

18+
from requests.exceptions import Timeout
1819
from requests_oauthlib import OAuth1Session
1920
from twitter_ads.utils import get_version
2021
from twitter_ads.error import Error
@@ -87,8 +88,11 @@ def __oauth_request(self):
8788
retry_max = self._client.options.get('retry_max', 0)
8889
retry_delay = self._client.options.get('retry_delay', 1500)
8990
retry_on_status = self._client.options.get('retry_on_status', [500, 503])
91+
retry_on_timeouts = self._client.options.get('retry_on_timeouts', False)
92+
timeout = self._client.options.get('timeout', None)
9093
retry_count = 0
9194
retry_after = None
95+
timeout = self._client.options.get('timeout', None)
9296

9397
consumer = OAuth1Session(
9498
self._client.consumer_key,
@@ -100,8 +104,20 @@ def __oauth_request(self):
100104
method = getattr(consumer, self._method)
101105

102106
while (retry_count <= retry_max):
103-
response = method(url, headers=headers, data=data, params=params,
104-
files=files, stream=stream)
107+
try:
108+
response = method(url, headers=headers, data=data, params=params,
109+
files=files, stream=stream, timeout=timeout)
110+
except Timeout as e:
111+
if retry_on_timeouts:
112+
if retry_count == retry_max:
113+
raise Exception(e)
114+
logger.warning("Timeout occurred: resume in %s seconds"
115+
% (int(retry_delay) / 1000))
116+
time.sleep(int(retry_delay) / 1000)
117+
retry_count += 1
118+
continue
119+
raise Exception(e)
120+
105121
# do not retry on 2XX status code
106122
if 200 <= response.status_code < 300:
107123
break

0 commit comments

Comments
 (0)