Skip to content

Commit bca3df4

Browse files
authored
Merge pull request #3 from singular-labs/504_refactor
Pool connections and manage retries properly
2 parents 3b35531 + 725cd85 commit bca3df4

File tree

3 files changed

+25
-3
lines changed

3 files changed

+25
-3
lines changed

singular_api_client/etl_manager.py

Lines changed: 12 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -103,6 +103,17 @@ def __init__(self, api_key,
103103
self.max_update_window_days = max_update_window_days
104104
self.state = self.load_state()
105105
self.should_stop = False
106+
session = requests.Session()
107+
retry = Retry(
108+
connect=5,
109+
backoff_factor=0.5,
110+
status_forcelist=(500, 502, 504),
111+
method_whitelist=('GET', 'POST')
112+
)
113+
adapter = HTTPAdapter(max_retries=retry)
114+
session.mount('http://', adapter)
115+
session.mount('https://', adapter)
116+
self.session = session
106117

107118
def handle_new_data(self, source, date, download_url, report_id):
108119
"""
@@ -124,7 +135,7 @@ def handle_new_data(self, source, date, download_url, report_id):
124135
:param report_id: Singular Internal Report ID, can be used for auditing
125136
:type date: str
126137
"""
127-
r = requests.get(download_url)
138+
r = self.session.get(download_url)
128139
if not r.ok:
129140
if r.status_code is None or (500 <= r.status_code < 600):
130141
raise UnexpectedAPIException("unexpected error when downloading report_id=%s, url=%s" % (

singular_api_client/singular_client.py

Lines changed: 12 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,17 @@ class SingularClient(object):
2323

2424
def __init__(self, api_key):
2525
self.api_key = api_key
26+
session = requests.Session()
27+
retry = Retry(
28+
connect=5,
29+
backoff_factor=0.5,
30+
status_forcelist=(500, 502, 504),
31+
method_whitelist=('GET', 'POST')
32+
)
33+
adapter = HTTPAdapter(max_retries=retry)
34+
session.mount('http://', adapter)
35+
session.mount('https://', adapter)
36+
self.session = session
2637

2738
def run_report(self, start_date, end_date,
2839
format=Format.JSON,
@@ -340,7 +351,7 @@ def __api_request(self, method, endpoint, **kwargs):
340351
headers = {"Authorization": self.api_key,
341352
'User-Agent': 'Singular API Client v%s' % __version__}
342353

343-
response = requests.request(method, url, headers=headers, **kwargs)
354+
response = self.session.request(method, url, headers=headers, **kwargs)
344355

345356
logger.info("%(method)s %(url)s, kwargs = %(kwargs)s --> code = %(code)s" %
346357
dict(method=method, url=url, kwargs=repr(kwargs), code=response.status_code))

singular_api_client/version.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1 +1 @@
1-
__version__ = "0.5.7"
1+
__version__ = "0.5.8"

0 commit comments

Comments
 (0)