[http] Ensure the file handle is always closed

Closes #4323
This commit is contained in:
pukkandan 2022-07-11 01:13:29 +05:30
parent 563e0bf82a
commit 6d645b5577
No known key found for this signature in database
GPG Key ID: 7EEE9E1E817D0A39

View File

@ -206,6 +206,12 @@ def establish_connection():
except RESPONSE_READ_EXCEPTIONS as err: except RESPONSE_READ_EXCEPTIONS as err:
raise RetryDownload(err) raise RetryDownload(err)
def close_stream():
if ctx.stream is not None:
if not ctx.tmpfilename == '-':
ctx.stream.close()
ctx.stream = None
def download(): def download():
data_len = ctx.data.info().get('Content-length', None) data_len = ctx.data.info().get('Content-length', None)
@ -239,12 +245,9 @@ def download():
before = start # start measuring before = start # start measuring
def retry(e): def retry(e):
to_stdout = ctx.tmpfilename == '-' close_stream()
if ctx.stream is not None: ctx.resume_len = (byte_counter if ctx.tmpfilename == '-'
if not to_stdout: else os.path.getsize(encodeFilename(ctx.tmpfilename)))
ctx.stream.close()
ctx.stream = None
ctx.resume_len = byte_counter if to_stdout else os.path.getsize(encodeFilename(ctx.tmpfilename))
raise RetryDownload(e) raise RetryDownload(e)
while True: while True:
@ -382,6 +385,9 @@ def retry(e):
continue continue
except SucceedDownload: except SucceedDownload:
return True return True
except: # noqa: E722
close_stream()
raise
self.report_error('giving up after %s retries' % retries) self.report_error('giving up after %s retries' % retries)
return False return False