chg: Put all open in with statements

pull/25/head
Raphaël Vinot 2017-12-21 15:12:57 +01:00
parent 9d65f2b79c
commit 56f0ebb442
1 changed files with 33 additions and 36 deletions

View File

@ -493,7 +493,7 @@ class File(FileBase):
def _metadata_exif(self, metadata_file_path):
"""Read exif metadata from a jpg or tiff file using exifread."""
# TODO: can we shorten this method somehow?
img = open(self.src_path, 'rb')
with open(self.src_path, 'rb') as img:
tags = None
try:
tags = exifread.process_file(img, debug=True)
@ -504,7 +504,6 @@ class File(FileBase):
tags = exifread.process_file(img, debug=True)
except Exception as e:
self.add_error(e, "Failed to get any metadata for file {}.".format(self.src_path))
img.close()
return False
for tag in sorted(tags.keys()):
# These tags are long and obnoxious/binary so we don't add them
@ -518,14 +517,13 @@ class File(FileBase):
metadata_file.write("Key: {}\tValue: {}\n".format(tag, tag_string))
# TODO: how do we want to log metadata?
self.set_property('metadata', 'exif')
img.close()
return True
def _metadata_png(self, metadata_file_path):
"""Extract metadata from a png file using PIL/Pillow."""
warnings.simplefilter('error', Image.DecompressionBombWarning)
try:
img = Image.open(self.src_path)
with Image.open(self.src_path) as img:
for tag in sorted(img.info.keys()):
# These are long and obnoxious/binary
if tag not in ('icc_profile'):
@ -533,7 +531,6 @@ class File(FileBase):
metadata_file.write("Key: {}\tValue: {}\n".format(tag, img.info[tag]))
# LOG: handle metadata
self.set_property('metadata', 'png')
img.close()
except Exception as e: # Catch decompression bombs
# TODO: only catch DecompressionBombWarnings here?
self.add_error(e, "Caught exception processing metadata for {}".format(self.src_path))
@ -580,8 +577,8 @@ class File(FileBase):
tempfile_path = os.path.join(tempdir_path, self.filename)
warnings.simplefilter('error', Image.DecompressionBombWarning)
try: # Do image conversions
img_in = Image.open(self.src_path)
img_out = Image.frombytes(img_in.mode, img_in.size, img_in.tobytes())
with Image.open(self.src_path) as img_in:
with Image.frombytes(img_in.mode, img_in.size, img_in.tobytes()) as img_out:
img_out.save(tempfile_path)
self.src_path = tempfile_path
except Exception as e: # Catch decompression bombs