From 123947100bdfb438f3b0d23101084256ac4cb12b Mon Sep 17 00:00:00 2001 From: Akim Juillerat Date: Wed, 18 Mar 2020 12:53:10 +0100 Subject: [PATCH] [FIX] attachment_s3: Close fileobjects after usage --- attachment_s3/models/ir_attachment.py | 36 +++++++++++++-------------- 1 file changed, 18 insertions(+), 18 deletions(-) diff --git a/attachment_s3/models/ir_attachment.py b/attachment_s3/models/ir_attachment.py index e7e4a1b..f31bb66 100644 --- a/attachment_s3/models/ir_attachment.py +++ b/attachment_s3/models/ir_attachment.py @@ -124,10 +124,10 @@ class IrAttachment(models.Model): ) if bin_size: return bucket.Object(key).content_length - res = io.BytesIO() - bucket.download_fileobj(key, res) - res.seek(0) - read = base64.b64encode(res.read()) + with io.BytesIO() as res: + bucket.download_fileobj(key, res) + res.seek(0) + read = base64.b64encode(res.read()) except ClientError: read = '' _logger.info( @@ -143,20 +143,20 @@ class IrAttachment(models.Model): if location == 's3': bucket = self._get_s3_bucket() obj = bucket.Object(key=key) - file = io.BytesIO() - file.write(bin_data) - file.seek(0) - filename = 's3://%s/%s' % (bucket.name, key) - try: - obj.upload_fileobj(file) - except ClientError as error: - # log verbose error from s3, return short message for user - _logger.exception( - 'Error during storage of the file %s' % filename - ) - raise exceptions.UserError( - _('The file could not be stored: %s') % str(error) - ) + with io.BytesIO() as file: + file.write(bin_data) + file.seek(0) + filename = 's3://%s/%s' % (bucket.name, key) + try: + obj.upload_fileobj(file) + except ClientError as error: + # log verbose error from s3, return short message for user + _logger.exception( + 'Error during storage of the file %s' % filename + ) + raise exceptions.UserError( + _('The file could not be stored: %s') % str(error) + ) else: _super = super(IrAttachment, self) filename = _super._store_file_write(key, bin_data)