Skip to content

Commit 26f4585

Browse files
author
Jussi Kukkonen
committed
Download: Don't leak requests.Responses
Use 'with' to avoid leaking responses when response.raise_for_status() is used. Signed-off-by: Jussi Kukkonen <[email protected]>
1 parent b5a3c70 commit 26f4585

File tree

1 file changed

+8
-19
lines changed

1 file changed

+8
-19
lines changed

tuf/download.py

Lines changed: 8 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -251,24 +251,21 @@ def _download_file(url, required_length, STRICT_REQUIRED_LENGTH=True):
251251
# Always stream to control how requests are downloaded:
252252
# http://docs.python-requests.org/en/master/user/advanced/#body-content-workflow
253253
#
254-
# We will always manually close Responses, so no need for a context
255-
# manager.
256-
#
257254
# Always set the timeout. This timeout value is interpreted by requests as:
258255
# - connect timeout (max delay before first byte is received)
259256
# - read (gap) timeout (max delay between bytes received)
260257
# These are NOT overall/total, wall-clock timeouts for any single read.
261258
# http://docs.python-requests.org/en/master/user/advanced/#timeouts
262-
response = session.get(
263-
url, stream=True, timeout=tuf.settings.SOCKET_TIMEOUT)
259+
with session.get(url, stream=True,
260+
timeout=tuf.settings.SOCKET_TIMEOUT) as response:
264261

265-
# Check response status.
266-
response.raise_for_status()
262+
# Check response status.
263+
response.raise_for_status()
267264

268-
# Download the contents of the URL, up to the required length, to a
269-
# temporary file, and get the total number of downloaded bytes.
270-
total_downloaded, average_download_speed = \
271-
_download_fixed_amount_of_data(response, temp_file, required_length)
265+
# Download the contents of the URL, up to the required length, to a
266+
# temporary file, and get the total number of downloaded bytes.
267+
total_downloaded, average_download_speed = \
268+
_download_fixed_amount_of_data(response, temp_file, required_length)
272269

273270
# Does the total number of downloaded bytes match the required length?
274271
_check_downloaded_length(total_downloaded, required_length,
@@ -382,16 +379,8 @@ def _download_fixed_amount_of_data(response, temp_file, required_length):
382379
break
383380

384381
except urllib3.exceptions.ReadTimeoutError as e:
385-
# Whatever happens, make sure that we always close the connection.
386-
response.close()
387382
raise tuf.exceptions.SlowRetrievalError(str(e))
388383

389-
except:
390-
# Whatever happens, make sure that we always close the connection.
391-
response.close()
392-
raise
393-
394-
response.close()
395384
return number_of_bytes_received, average_download_speed
396385

397386

0 commit comments

Comments
 (0)