Last active
November 30, 2023 09:23
-
-
Save phainamikaze/e56f26e8b9cd431721ab1c0ff4bcb612 to your computer and use it in GitHub Desktop.
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 urllib.parse | |
import boto3 | |
import os | |
print('Loading function') | |
s3 = boto3.client('s3') | |
TOPIC_ARN = os.environ['topicARN'] | |
def lambda_handler(event, context): | |
#print("Received event: " + json.dumps(event, indent=2)) | |
# Get the object from the event and show its content type | |
bucket = event['Records'][0]['s3']['bucket']['name'] | |
key = urllib.parse.unquote_plus(event['Records'][0]['s3']['object']['key'], encoding='utf-8') | |
try: | |
response = s3.get_object(Bucket=bucket, Key=key) | |
s3_object_body = response.get('Body') | |
content_str = s3_object_body.read().decode() | |
print("content String: " + content_str) | |
words = len(content_str.split()) | |
result = "The word count in the "+ key +" file is "+ str(words) | |
print(result) | |
snsClient = boto3.client('sns') | |
response = snsClient.publish( | |
TopicArn = TOPIC_ARN, | |
Subject = 'The word count', | |
Message = result | |
) | |
return result | |
except Exception as e: | |
print(e) | |
print('Error getting object {} from bucket {}. Make sure they exist and your bucket is in the same region as this function.'.format(key, bucket)) | |
raise e |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment