Raise Exception if letter PDF not in S3

Previously, the function would just return a presumed filename. Now that
it actually checks s3, if the file doesn't exist it'll raise an
exception. By default that's a StopIteration at the end of the bucket
iterator, which isn't ideal as this will get supressed if the function
is called within a generator loop further up or anything.

There are a couple of places where we expect the file may not exist, so
we define a custom exception to rescue specifically here. I did consider
subclassing boto's ClientError, but this wasn't straightforward as the
constructor expects to know the operation that failed, which for me is a
signal that it's not an appropriate (re-)use of the class.
This commit is contained in:
Leo Hemsted
2021-03-08 18:09:16 +00:00
committed by Ben Thorner
parent b43a367d5f
commit 6784ae62a6
4 changed files with 32 additions and 4 deletions

View File

@@ -37,6 +37,10 @@ def get_folder_name(created_at):
return '{}/'.format(print_datetime.date())
class LetterPDFNotFound(Exception):
pass
def find_letter_pdf_filename(notification):
"""
Retrieve the filename of a letter from s3 by searching for it based on a prefix.
@@ -47,7 +51,10 @@ def find_letter_pdf_filename(notification):
s3 = boto3.resource('s3')
bucket = s3.Bucket(bucket_name)
item = next(x for x in bucket.objects.filter(Prefix=prefix))
try:
item = next(x for x in bucket.objects.filter(Prefix=prefix))
except StopIteration:
raise LetterPDFNotFound(f'File not found in bucket {bucket_name} with prefix {prefix}', )
return item.key