From 053a8718c9d793d0e958fc94718cb22ea5f78716 Mon Sep 17 00:00:00 2001 From: NJX-njx <3771829673@qq.com> Date: Tue, 3 Mar 2026 22:09:16 +0800 Subject: [PATCH] fix: handle NoSuchKey when image_features.pkl is missing in S3 (fixes #14) - Add ClientError exception handling for s3.get_object() in product_lookup - Return user-friendly 503 error when image_features.pkl does not exist - Prevents 500 debug traceback exposure when image preprocessing not run Made-with: Cursor --- backend/app.py | 21 ++++++++++++++++++--- 1 file changed, 18 insertions(+), 3 deletions(-) diff --git a/backend/app.py b/backend/app.py index e7a86ad..3493ec1 100644 --- a/backend/app.py +++ b/backend/app.py @@ -10,7 +10,7 @@ import json from models import Product, Category, User, db, Comment, product_categories import boto3 -from botocore.exceptions import NoCredentialsError +from botocore.exceptions import NoCredentialsError, ClientError from vulnerable_image_processor import process_image from sklearn.metrics.pairwise import cosine_similarity import pickle @@ -236,8 +236,23 @@ def product_lookup(): features_file_key = 'image_features.pkl' # S3 key for the features file - response = s3.get_object(Bucket=bucket_name, Key=features_file_key) - features = pickle.loads(response['Body'].read()) + try: + response = s3.get_object(Bucket=bucket_name, Key=features_file_key) + features = pickle.loads(response['Body'].read()) + except ClientError as e: + if e.response['Error']['Code'] == 'NoSuchKey': + app.logger.error( + 'image_features.pkl not found in S3 bucket %s. ' + 'Please run the image preprocessing pipeline in the SageMaker notebook first.', + bucket_name + ) + return jsonify({ + 'error': ( + 'Image features file not found. Please run the image preprocessing ' + 'pipeline in the SageMaker notebook first. See README for setup instructions.' + ) + }), 503 + raise payload = { 'bucket_name': bucket_name,