-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathlambda_function.py
66 lines (59 loc) · 2.66 KB
/
lambda_function.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
import json
import boto3
from urllib.parse import unquote_plus
from botocore.exceptions import ClientError
s3 = boto3.client('s3')
dynamodb = boto3.resource('dynamodb')
table_name = os.environ['TABLE_NAME']
table = dynamodb.Table(table_name)
def lambda_handler(event, context):
for record in event['Records']:
bucket_name = record['s3']['bucket']['name']
object_key = unquote_plus(record['s3']['object']['key'])
file_name, user_id = object_key.split('/', 1)
try:
response = s3.head_object(Bucket=bucket_name, Key=object_key)
metadata = response['Metadata']
content_type = response['ContentType']
content_length = response['ContentLength']
last_modified = response['LastModified']
created_at = last_modified.isoformat()
try:
table.update_item(
Key={
'file_name': file_name,
'user_id': user_id
},
UpdateExpression="set created_at = :created_at, file_content_length = :content_length, file_size = :file_size, file_type = :file_type",
ExpressionAttributeValues={
':created_at': created_at,
':content_length': content_length,
':file_size': content_length,
':file_type': content_type
},
ConditionExpression="attribute_exists(file_name) AND attribute_exists(user_id)",
ReturnValues="ALL_NEW"
)
print(f"Metadata for {object_key} updated in DynamoDB table {table_name}")
except ClientError as e:
if e.response['Error']['Code'] == 'ConditionalCheckFailedException':
table.put_item(
Item={
'file_name': file_name,
'user_id': user_id,
'created_at': created_at,
'file_content_length': content_length,
'file_size': content_length,
'file_type': content_type
}
)
print(f"Metadata for {object_key} inserted in DynamoDB table {table_name}")
else:
raise
except Exception as e:
print(f"Error processing object {object_key} from bucket {bucket_name}. Error: {str(e)}")
raise e
return {
'statusCode': 200,
'body': json.dumps('Lambda function executed successfully!')
}