Skip to content

Instantly share code, notes, and snippets.

@ola0x
Created October 9, 2021 02:56
Show Gist options
  • Save ola0x/dc9774e6d3f9a94d937305e4ac54f350 to your computer and use it in GitHub Desktop.
Save ola0x/dc9774e6d3f9a94d937305e4ac54f350 to your computer and use it in GitHub Desktop.
This is a Lambda function that's get triggers when a file is uploaded to an s3 bucket. I wrote it in such a way that if an image or a json file is uploaded to the s3 bucket the lambda func is able to process it.
import json
import urllib.parse
import boto3
print('Loading function')
s3 = boto3.client('s3')
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)
condition = response['ContentType']
if(condition) == "image/jpeg":
print("CONTENT TYPE: " + response['ContentType'])
return "Success, read an Image"
elif(condition) == "application/json":
text = response['Body'].read().decode()
data = json.loads(text)
print(data)
transaction = data['transactions']
for record in transaction:
print(record['transType'])
return "Success, read a json"
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