-
Notifications
You must be signed in to change notification settings - Fork 2
/
logger.py
141 lines (129 loc) · 3.9 KB
/
logger.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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
#!/usr/bin/env python
# -*- coding: UTF-8 -*-
#
# "Josep Valls-Vargas" <josep@valls.name>
#
import json
try:
import boto3
except:
boto3 = None
pass
TABLE_NAME = 'logger_v1'
def lambda_handler(event, context):
log_event(event)
body = AlexaResponse("Hello","This is an Alexa response.").toAlexa()
return {'statusCode':200,'headers':{'Content-Type': 'application/json'},'body':json.dumps(body)}
import decimal
def replace_decimals(obj):
if isinstance(obj, list):
for i in xrange(len(obj)):
obj[i] = replace_decimals(obj[i])
return obj
elif isinstance(obj, dict):
for k in obj.iterkeys():
obj[k] = replace_decimals(obj[k])
return obj
elif isinstance(obj, decimal.Decimal):
if obj % 1 == 0:
return int(obj)
else:
return float(obj)
else:
return obj
def log_event(event, log_key='log', last_key='last'):
if last_key:
persist_document(last_key, event)
log = load_document(log_key) or {}
if 'req_history' not in log or not log['req_history']: log['req_history'] = []
log['req_history'].append(event)
persist_document(log_key,log)
def check_table():
dynamodb = boto3.resource('dynamodb')
try:
table = dynamodb.Table(TABLE_NAME)
table.creation_date_time
except:
table = dynamodb.create_table(
TableName=TABLE_NAME,
KeySchema=[
{
'AttributeName': 'key',
'KeyType': 'HASH'
},
],
AttributeDefinitions=[
{
'AttributeName': 'key',
'AttributeType': 'S'
},
],
ProvisionedThroughput={
'ReadCapacityUnits': 5,
'WriteCapacityUnits': 5
}
)
table = dynamodb.Table(TABLE_NAME)
return table
def load_document(key):
if boto3 is not None:
try:
table = check_table()
response = table.get_item(
Key={
'key': key,
}
)
if 'Item' in response:
document = replace_decimals(response['Item']['document'])
else:
document = {}
return document
except Exception as e:
print "Exception",e
return None
def persist_document(key, document):
if boto3 is not None:
if not key:
key = 'empty'
dynamodb = boto3.resource('dynamodb')
table = check_table()
table.put_item(
Item={'key': key, 'document': document}
)
return True
else:
return False
class AlexaResponse(object):
def __init__(self, title, response, reprompt=None, model=None, ssml=None, card=None):
self.title = title
self.response = response
self.reprompt = reprompt
self.model = model
self.ssml = ssml
self.card = card
def __str__(self):
return "%s: %s" % (self.title, self.response)
def toAlexa(self):
return {
"version": "1.0",
"sessionAttributes": {'model': (self.model.serialize() if self.model else {})},
"response": {
"outputSpeech": {
"type": "PlainText",
"text": self.response
},
"card": {
"type": "Simple",
"title": self.title,
"content": self.response if not self.card else self.card
},
"reprompt": {
"outputSpeech": {
"type": "PlainText",
"text": (self.reprompt or self.response)
}
},
"shouldEndSession": ((not self.model.running) if self.model else True)
}
}