Created
May 17, 2022 08:35
-
-
Save ojmccall/347058a8683ab9f750e3211e93cace3a to your computer and use it in GitHub Desktop.
lambda function to unzip file from SFMC
This file contains 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 urllib | |
import zipfile | |
import boto3 | |
import io | |
s3 = boto3.client('s3') | |
def lambda_handler(event, context): | |
bucket = event['Records'][0]['s3']['bucket']['name'] | |
key = urllib.parse.quote_plus(event['Records'][0]['s3']['object']['key'].encode('utf8')) | |
if key.find(".zip") >0: | |
try: | |
obj = s3.get_object(Bucket=bucket, Key=key) | |
putObjects = [] | |
with io.BytesIO(obj["Body"].read()) as tf: | |
# rewind the file | |
tf.seek(0) | |
# Read the file as a zipfile and process the members | |
with zipfile.ZipFile(tf, mode='r') as zipf: | |
for file in zipf.infolist(): | |
fileName = file.filename | |
putFile = s3.put_object(Bucket=bucket, Key=fileName, Body=zipf.read(file)) | |
putObjects.append(putFile) | |
print(putFile) | |
# Delete zip file after unzip | |
if len(putObjects) > 0: | |
deletedObj = s3.delete_object(Bucket=bucket, Key=key) | |
print('deleted file:') | |
print(deletedObj) | |
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