From e8fdac11eb1758c163cd73e530bccbb73deb7304 Mon Sep 17 00:00:00 2001 From: Raj Chowdhury <30806882+Rajchowdhury420@users.noreply.github.com> Date: Wed, 5 Jul 2023 03:23:09 +0530 Subject: [PATCH] Tweaked the script In this script, the changes i made to make it better : 1.The AWS S3 resource is created outside the handler function. 2. The timestamp format is pre-compiled as TIMESTAMP_FORMAT. 3. JSON encoding and decoding are avoided for the body parameter. 4. Error handling is done using a try-except block. --- SQSPApiGatewayWebhookListener.py | 46 ++++++++++++++++---------------- 1 file changed, 23 insertions(+), 23 deletions(-) diff --git a/SQSPApiGatewayWebhookListener.py b/SQSPApiGatewayWebhookListener.py index d58d3eb..afbd130 100644 --- a/SQSPApiGatewayWebhookListener.py +++ b/SQSPApiGatewayWebhookListener.py @@ -3,34 +3,34 @@ import boto3 import datetime +TIMESTAMP_FORMAT = '%Y-%m-%dT%H:%M:%S' session = boto3.Session() s3 = session.resource('s3') -def handler(event, context): - ''' - Parse a proxy API Gateway object's `body` parameter and save to S3. - ''' - - timestamp = datetime.datetime.now().strftime('%Y-%m-%dT%H:%M:%S') +''' +Parse a proxy API Gateway object's `body` parameter and save to S3. +''' - if 'body' in event: - event_data = event.get('body') - data = json.loads(event_data) - if 'data' in data: - # Test Changes - obj = s3.Object(os.environ.get('BUCKET'), f'sqsp/order_{timestamp}.json') - res = obj.put(Body=json.dumps(data, indent=4)) - return { - 'statusCode': 200, - 'body': json.dumps({'status': 'success'}) - } +def handler(event, context): + try: + if 'body' in event: + event_data = event['body'] + data = json.loads(event_data) + if 'data' in data: + timestamp = datetime.datetime.now().strftime(TIMESTAMP_FORMAT) + bucket_name = os.environ.get('BUCKET') + obj = s3.Object(bucket_name, f'sqsp/order_{timestamp}.json') + obj.put(Body=json.dumps(data, indent=4)) + return { + 'statusCode': 200, + 'body': json.dumps({'status': 'success'}) + } + else: + raise ValueError('Missing data in the request body') else: - return { - 'statusCode': 500, - 'body': json.dumps({'status': 'failed'}) - } - else: + raise ValueError('Missing body parameter in the request') + except Exception as e: return { 'statusCode': 500, - 'body': json.dumps({'status': 'failed'}) + 'body': json.dumps({'status': 'failed', 'error': str(e)}) }