-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlambda_get_post_handler.py
More file actions
79 lines (65 loc) · 2.38 KB
/
lambda_get_post_handler.py
File metadata and controls
79 lines (65 loc) · 2.38 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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
"""Lambda function to handle POST and GET"""
import json
from decimal import Decimal
import boto3
import uuid
from boto3.dynamodb.conditions import Key, Attr
# import datetime
dynamodb = boto3.resource("dynamodb")
table = dynamodb.Table("upload-table-sh")
def lambda_handler(event, context):
"""Handles incoming request"""
if event["httpMethod"] == "POST":
response = post_handler(event, context)
body = event["body"]
elif event["httpMethod"] == "GET":
response = get_handler(event, context)
# aws require content in body be string type
body = json.dumps(response["Item"], cls=CustomJsonEncoder)
# reformat for lambda proxy response
format_response = {
"isBase64Encoded": False,
"statusCode": response["HTTPStatusCode"],
"headers": response["HTTPHeaders"],
"body": body,
}
return format_response
def post_handler(event, context):
"""Sent data from API Gateway to the table"""
data = json.loads(event["body"])
data = convert_empty_values(data)
data["uuidID"] = str(uuid.uuid4())
response = table.put_item(Item=data)
return response["ResponseMetadata"]
def get_handler(event, context):
queries = event["queryStringParameters"]
if queries["passBuild"] != "true":
response = table.query(
KeyConditionExpression=Key("assignment").eq(queries["assignment"]))
else:
response = table.query(
KeyConditionExpression=Key("assignment").eq(queries["assignment"]),
FilterExpression=Attr('report').contains(
'"numberOfFailures" : { "N" : "0" }')
)
# Add item fetched to the return statement
response["ResponseMetadata"]["Item"] = response["Items"]
return response["ResponseMetadata"]
def convert_empty_values(raw):
"""Convert empty values to Null for Nosql"""
if isinstance(raw, dict):
for k, v in raw.items():
raw[k] = convert_empty_values(v)
elif isinstance(raw, list):
for i in range(len(raw)):
raw[i] = convert_empty_values(raw[i])
elif raw == "":
raw = None
return raw
class CustomJsonEncoder(json.JSONEncoder):
"""JSONEncoder for get item"""
def default(self, obj):
"""Convert Decimal to float"""
if isinstance(obj, Decimal):
return float(obj)
return super(CustomJsonEncoder, self).default(obj)