Skip to content

Commit 34c6937

Browse files
author
Benjamin Moody
committed
RangeTransfer: fix exception handling.
If a normal exception occurs while reading an HTTP response, we want to read the remaining data so that the connection can be reused for another transfer. If the RangeTransfer is deleted without calling close() or __exit__(), the response object must still be explicitly closed so that it no longer counts against the connection pool limit. This doesn't happen automatically when a Response is garbage-collected, which is probably a bug in python-requests.
1 parent 390411e commit 34c6937

File tree

1 file changed

+13
-5
lines changed

1 file changed

+13
-5
lines changed

wfdb/io/_url.py

Lines changed: 13 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -151,10 +151,11 @@ def __init__(self, url, start, end):
151151
}
152152

153153
session = _get_session()
154-
response = session.request(method, url, headers=headers, stream=True)
155-
self._content_iter = response.iter_content(4096)
154+
self._response = session.request(method, url, headers=headers,
155+
stream=True)
156+
self._content_iter = self._response.iter_content(4096)
156157
try:
157-
self._parse_headers(method, response)
158+
self._parse_headers(method, self._response)
158159
except Exception:
159160
self.close()
160161
raise
@@ -264,7 +265,7 @@ def close(self):
264265
pass
265266
except Exception:
266267
pass
267-
self._content_iter = iter([])
268+
self._response.close()
268269

269270
def __enter__(self):
270271
return self
@@ -273,9 +274,16 @@ def __exit__(self, exc_type, exc_val, exc_tb):
273274
# When exiting with a normal exception, shut down cleanly by
274275
# reading leftover response data. When exiting abnormally
275276
# (SystemExit, KeyboardInterrupt), do nothing.
276-
if not exc_type or isinstance(exc_type, Exception):
277+
if not exc_type or issubclass(exc_type, Exception):
277278
self.close()
278279

280+
def __del__(self):
281+
# If the object is deleted without calling close(), forcibly
282+
# close the existing connection.
283+
response = getattr(self, '_response', None)
284+
if response:
285+
response.close()
286+
279287
def iter_chunks(self):
280288
"""
281289
Iterate over the response body as a sequence of chunks.

0 commit comments

Comments
 (0)