-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathlambda_function.py
More file actions
51 lines (39 loc) · 1.74 KB
/
lambda_function.py
File metadata and controls
51 lines (39 loc) · 1.74 KB
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
import json
import boto3
def lambda_handler(event, context):
try:
bucket_name = event["Records"][0]["s3"]["bucket"]["name"]
file_name = event["Records"][0]["s3"]["object"]["key"]
s3 = boto3.client("s3")
response = s3.get_object(Bucket=bucket_name, Key=file_name)
content = response["Body"].read().decode("utf-8")
employees_data = json.loads(content)
department_totals = {}
for employee in employees_data:
department = employee.get("department")
salary = employee.get("salary")
if (
salary is None
or not isinstance(salary, (int, float))
or department is None
or not isinstance(department, (str))
):
raise ValueError("Invalid/missing data for department or salary..")
if department not in department_totals:
department_totals[department] = salary
else:
department_totals[department] += salary
# Sort the department totals by total salary
sorted_departments = dict(
sorted(department_totals.items(), key=lambda x: x[1], reverse=True)
)
print(f"Department-wise salary totals: {sorted_departments}")
return {"statusCode": 200, "body": json.dumps(sorted_departments)}
except ValueError as ve:
error_message = f"Value error occurred: {str(ve)}"
print(error_message)
return {"statusCode": 400, "body": json.dumps({"error": error_message})}
except Exception as e:
error_message = f"An unexpected error occurred: {str(e)}"
print(error_message)
return {"statusCode": 500, "body": json.dumps({"error": error_message})}