-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhandler.py
197 lines (159 loc) · 5.11 KB
/
handler.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
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
import json
import os
import logging
from datetime import datetime
from decimal import Decimal
import boto3
from botocore.exceptions import ClientError
from lambda_decorators import cors_headers
log_level = os.environ.get('LOG_LEVEL', 'INFO')
logging.root.setLevel(logging.getLevelName(log_level))
_logger = logging.getLogger(__name__)
def decimal_encode(obj):
if isinstance(obj, Decimal):
return int(obj)
raise TypeError
IS_OFFLINE = os.environ.get('IS_OFFLINE')
IS_LOCAL = os.environ.get('IS_LOCAL')
aws_region = os.environ.get('LAMBDA_AWS_REGION', 'us-east-1')
table_name = os.environ.get('VISITS_TABLE', 'crc_visits')
if((IS_LOCAL) or (IS_OFFLINE)):
ddb = boto3.resource('dynamodb',
endpoint_url='http://localhost:8000',
region_name='localhost',
aws_access_key_id='foo',
aws_secret_access_key='bar')
ddb_table = ddb.Table(table_name)
_logger.debug('DDB Connect: {}'.format(ddb_table))
else:
ddb = boto3.resource('dynamodb', region_name=aws_region)
ddb_table = ddb.Table(table_name)
_logger.debug('DDB Connect: {}'.format(ddb_table))
def put_item(data):
item = {}
item['site'] = data
item['counter'] = 0
item['last_updated'] = int(datetime.utcnow().timestamp())
res = ddb_table.put_item(
Item = item
)
_logger.info('DDB Put response: {}'.format(res))
return item
def get_items():
try:
res = ddb_table.scan()
data = res['Items']
while 'LastEvaluatedKey' in res:
res = ddb_table.scan(ExclusiveStartKey=res['LastEvaluatedKey'])
data.extend(res['Items'])
_logger.info('DDB Get response: {}'.format(data))
if not bool(data):
return { 'error': { 'message': 'items not found' } }
else:
return data
except ClientError as err:
return err.response['Error']
def get_item(data):
try:
res = ddb_table.get_item(
Key={
'site': data
}
)
data = res.get('Item', {})
_logger.info('DDB Get response: {}'.format(data))
if not bool(data):
return { 'error': { 'message': 'item not found' } }
else:
return data
except ClientError as err:
return err.response['Error']
def update_item(data):
site = data
time_now = int(datetime.utcnow().timestamp())
try:
res = ddb_table.update_item(
Key={
'site': site
},
UpdateExpression='ADD #c :c SET last_updated = :t',
ExpressionAttributeNames={
# Since counter is a reserved keyword
'#c': 'counter'
},
ExpressionAttributeValues={
':t': time_now,
':c': 1
},
ReturnValues="ALL_NEW"
)
_logger.info('DDB Put response: {}'.format(res))
return res['Attributes']
except ClientError as err:
return err.response['Error']
@cors_headers
def hello(event, context):
_logger.info('Event: {}'.format(json.dumps(event)))
body = {
"message": "Go Serverless v1.0! Your function executed successfully!",
# "date": int(datetime.utcnow().timestamp()),
"input": event
}
response = {
"statusCode": 200,
"body": json.dumps(body)
}
_logger.info('Response: {}'.format(json.dumps(response)))
return response
@cors_headers
def add_site(event, context):
_logger.info('Event: {}'.format(json.dumps(event)))
data = json.loads(event['body'])
site = data['website']
body = put_item(site)
response = {
"statusCode": 200,
"body": json.dumps(body, default=decimal_encode)
}
_logger.info('Response: {}'.format(json.dumps(response)))
return response
@cors_headers
def get_sites(event, context):
_logger.info('Event: {}'.format(json.dumps(event)))
body = get_items()
response = {
"statusCode": 200,
"body": json.dumps(body, default=decimal_encode)
}
_logger.info('Response: {}'.format(json.dumps(response)))
return response
@cors_headers
def get_site(event, context):
_logger.info('Event: {}'.format(json.dumps(event)))
site = event['pathParameters']['website']
body = get_item(site)
response = {
"statusCode": 200,
"body": json.dumps(body, default=decimal_encode)
}
_logger.info('Response: {}'.format(json.dumps(response)))
return response
@cors_headers
def update_site(event, context):
_logger.info('Event: {}'.format(json.dumps(event)))
data = json.loads(event['body'])
if 'website' not in data:
body = { 'error': { 'message':'incorrect schema' } }
response = {
"statusCode": 400,
"body": json.dumps(body, default=decimal_encode)
}
else:
site = data['website']
body = update_item(site)
response = {
"statusCode": 200,
"body": json.dumps(body, default=decimal_encode)
}
_logger.info('Response: {}'.format(json.dumps(response)))
return response