-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.py
59 lines (52 loc) · 1.89 KB
/
index.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
import boto3
import json
import decimal
from boto3.dynamodb.types import TypeDeserializer
dynamo = boto3.client('dynamodb')
#Comment goes here
class DecimalEncoder(json.JSONEncoder):
def default(self, o):
if isinstance(o, decimal.Decimal):
return str(o)
return super(DecimalEncoder, self).default(o)
def dynamo_obj_to_python_obj(dynamo_obj: dict) -> dict:
deserializer = TypeDeserializer()
return {
k: deserializer.deserialize(v)
for k, v in dynamo_obj.items()
}
def respond(err, res, tablename):
if not err:
results = {
tablename.capitalize(): res
}
return {
'statusCode': '400' if err else '200',
'body': err.message if err else json.dumps(results, cls=DecimalEncoder),
'headers': {
'Content-Type': 'application/json',
},
}
def lambda_handler(event, context):
#print("Received event: " + json.dumps(event, indent=2))
operations = {
'DELETE': lambda dynamo, x: dynamo.delete_item(**x),
'GET': lambda dynamo, x: dynamo.scan(**x),
'POST': lambda dynamo, x: dynamo.put_item(**x),
'PUT': lambda dynamo, x: dynamo.update_item(**x)
}
operation = event['httpMethod']
urlpath = event['path']
table = urlpath.split('/')[-1]
dbparam = {'TableName': table}
print('Assuming Scan of Table:', table)
if operation in operations:
payload = dbparam if operation == 'GET' else json.loads(event['body'])
dbitems = operations[operation](dynamo, payload)
new_format = []
for i in range(len(dbitems['Items'])):
new_format.append(dynamo_obj_to_python_obj(dbitems['Items'][i]))
#print('Converted records', json.dumps(new_format, cls=DecimalEncoder))
return respond(None, new_format, table)
else:
return respond(ValueError('Unsupported method "{}"'.format(operation)))