Skip to content

Commit 0b77eb9

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 8692663 commit 0b77eb9

File tree

1 file changed

+4
-15
lines changed

1 file changed

+4
-15
lines changed

tuf/ngclient/_internal/download.py

Lines changed: 4 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -24,13 +24,14 @@
2424
"""
2525
import logging
2626
import tempfile
27+
from contextlib import contextmanager
2728
from urllib import parse
2829

2930
from tuf import exceptions
3031

3132
logger = logging.getLogger(__name__)
3233

33-
34+
@contextmanager
3435
def download_file(url, required_length, fetcher):
3536
"""
3637
<Purpose>
@@ -66,31 +67,19 @@ def download_file(url, required_length, fetcher):
6667
url = parse.unquote(url).replace("\\", "/")
6768
logger.debug("Downloading: %s", url)
6869

69-
# This is the temporary file that we will return to contain the contents of
70-
# the downloaded file.
71-
temp_file = tempfile.TemporaryFile() # pylint: disable=consider-using-with
72-
7370
number_of_bytes_received = 0
7471

75-
try:
72+
with tempfile.TemporaryFile() as temp_file:
7673
chunks = fetcher.fetch(url, required_length)
7774
for chunk in chunks:
7875
temp_file.write(chunk)
7976
number_of_bytes_received += len(chunk)
80-
8177
if number_of_bytes_received > required_length:
8278
raise exceptions.DownloadLengthMismatchError(
8379
required_length, number_of_bytes_received
8480
)
85-
86-
except Exception:
87-
# Close 'temp_file'. Any written data is lost.
88-
temp_file.close()
89-
raise
90-
91-
else:
9281
temp_file.seek(0)
93-
return temp_file
82+
yield temp_file
9483

9584

9685
def download_bytes(url, required_length, fetcher):

0 commit comments

Comments
 (0)