From 79b086bd5b6ef1ac99c650bd140fe1cbf998144b Mon Sep 17 00:00:00 2001 From: Niccolo' Zanotti Date: Wed, 4 Sep 2024 15:04:20 +0200 Subject: [PATCH] Trying to handle exception if LOG_FILE_KEY does not exist in the bucket yet. --- lambda_function.py | 14 ++++++++++++-- 1 file changed, 12 insertions(+), 2 deletions(-) diff --git a/lambda_function.py b/lambda_function.py index 23e6b49..49bbf9c 100644 --- a/lambda_function.py +++ b/lambda_function.py @@ -1,11 +1,13 @@ import json + +import botocore from flask import Flask, request from flask_cors import CORS import boto3 import csv from datetime import datetime, timezone from awsgi import response - +import botocore.exceptions app = Flask(__name__) CORS(app, resources={r"/*": {"origins": "*"}}, supports_credentials=True) @@ -63,12 +65,20 @@ def append_log_to_s3(log_entry): LOG_FILE_KEY = f'{today.strftime("%Y-%m-%d")}-logs.csv' log_file = f'/tmp/{LOG_FILE_KEY}' # Temporary file path - # Download the existing log file from S3 if it exists + # Attempt to download the existing log file from S3 if it exists try: s3.download_file(BUCKET_NAME, LOG_FILE_KEY, log_file) file_exists = True except s3.exceptions.NoSuchKey: + # The file doesn't exist in S3; create a new one file_exists = False + except botocore.exceptions.ClientError as e: + if e.response['Error']['Code'] == '404': + # The file doesn't exist in S3; create a new one + file_exists = False + else: + # If it's a different error, re-raise it + raise # Append the log entry to the file with open(log_file, 'a', newline='') as file: