Skip to content

Commit cd44c9d

Browse files
committed
Implement download_file as contextmanager
It allows us to remove the disable of pylint consider-using-with warning and does not require any manual file closing. Signed-off-by: Teodora Sechkova <tsechkova@vmware.com>
1 parent 8a77ee9 commit cd44c9d

1 file changed

Lines changed: 5 additions & 16 deletions

File tree

tuf/ngclient/_internal/download.py

Lines changed: 5 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,7 @@
2424
"""
2525
import logging
2626
import tempfile
27+
from contextlib import contextmanager
2728
from urllib import parse
2829

2930
from tuf import exceptions
@@ -46,6 +47,7 @@ def __init__(self, fetcher):
4647

4748
self._fetcher = fetcher
4849

50+
@contextmanager
4951
def download_file(self, url, required_length):
5052
"""Opens a connection to 'url' and downloads the content
5153
up to 'required_length'.
@@ -71,33 +73,20 @@ def download_file(self, url, required_length):
7173
url = parse.unquote(url).replace("\\", "/")
7274
logger.debug("Downloading: %s", url)
7375

76+
number_of_bytes_received = 0
7477
# This is the temporary file that we will return to contain the
7578
# contents of the downloaded file.
76-
temp_file = (
77-
tempfile.TemporaryFile()
78-
) # pylint: disable=consider-using-with
79-
80-
number_of_bytes_received = 0
81-
82-
try:
79+
with tempfile.TemporaryFile() as temp_file:
8380
chunks = self._fetcher.fetch(url, required_length)
8481
for chunk in chunks:
8582
temp_file.write(chunk)
8683
number_of_bytes_received += len(chunk)
87-
8884
if number_of_bytes_received > required_length:
8985
raise exceptions.DownloadLengthMismatchError(
9086
required_length, number_of_bytes_received
9187
)
92-
93-
except Exception:
94-
# Close 'temp_file'. Any written data is lost.
95-
temp_file.close()
96-
raise
97-
98-
else:
9988
temp_file.seek(0)
100-
return temp_file
89+
yield temp_file
10190

10291
def download_bytes(self, url, required_length):
10392
"""Download bytes from given url

0 commit comments

Comments
 (0)