/
python-dynamodb.py
58 lines (47 loc) · 1.73 KB
/
python-dynamodb.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
from __future__ import print_function
import boto3
import json
import uuid
from decimal import *
# Monkey patch Decimal's default Context to allow
# inexact and rounded representation of floats
from boto3.dynamodb.types import DYNAMODB_CONTEXT
# Inhibit Inexact Exceptions
DYNAMODB_CONTEXT.traps[Inexact] = 0
# Inhibit Rounded Exceptions
DYNAMODB_CONTEXT.traps[Rounded] = 0
def lambda_handler(event, context):
dynamo = boto3.resource('dynamodb').Table('senseware')
# When testing thorugh the lambda UI the packet is the event but when testing through the Api Gateway the packet
# is wrapped in an additional request metadata dictionary
try:
packet = json.loads(event['body'])
except KeyError:
packet = event
for record in packet['data']:
for key in ['value', 'raw']:
if record[key] != "" and record[key] != None:
# DynamoDb wants decimals, not floats
record[key] = Decimal(record[key])
else:
del record[key]
for key in ['pkt', 'ts']:
if record[key] == "" or record[key] == None:
del record[key]
# Add the streams meta data to every record (optional)
for key in ['sn', 'site', 'location', 'mod', 'sid', 'type', 'cid', 'name', 'unit']:
if packet[key] != "" and packet[key] != None:
# DynamoDb wants decimals, not floats
record[key] = packet[key]
# Give this record an ID
record['partition'] = str(uuid.uuid4())
# Put it into the database
dynamo.put_item(
TableName='senseware',
Item=record
)
# Return a Success Message
return {
"statusCode": 200,
"body": ""
}