Created
March 14, 2022 23:07
-
-
Save nktstudios/356b652ac9ff2db093e32074bb8857d9 to your computer and use it in GitHub Desktop.
AWS s3 Put Event Lambda Code
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import json | |
import boto3 | |
def lambda_handler(event, context): | |
#1 create an s3 client object | |
s3 = boto3.client("s3") | |
#2 counters for the calculations | |
addition_count = 0 | |
multiplication_count = 0 | |
#3 Get the bucket name | |
bucket_name = event['Records'][0]['s3']['bucket']['name'] | |
#4 Get the file name | |
key = event['Records'][0]['s3']['object']['key'] | |
try: | |
#5 Fetch the file from s3 | |
response = s3.get_object(Bucket = bucket_name, Key = key) | |
#6 Deserialise the file's contents | |
contents = response["Body"].read().decode() | |
#7 Parse the contents to dictionary | |
data = json.loads(contents) | |
#8 Print the dictionary | |
print(data) | |
#9 Process the dictionary | |
calculations = data['calculations'] | |
for record in calculations: | |
if record['operation'] == 'ADDITION': | |
addition_count += 1 | |
first_num = record['first_num'] | |
second_num = record['second_num'] | |
result = first_num + second_num | |
print("Addition of: {} and {} = {} ".format(first_num, second_num, result)) | |
elif record['operation'] == 'MULTIPLICATION': | |
multiplication_count +=1 | |
first_num = record['first_num'] | |
second_num = record['second_num'] | |
result = first_num * second_num | |
print("Multiplication of: {} and {} = {} ".format(first_num, second_num, result)) | |
except Exception as e: | |
print(e) | |
return { | |
'statusCode': 200, | |
'body': json.dumps("Addition operations: {}, Multiplication operations: {}".format( | |
addition_count, multiplication_count)) | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment