-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlambda_function.py
More file actions
78 lines (68 loc) · 2.12 KB
/
lambda_function.py
File metadata and controls
78 lines (68 loc) · 2.12 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
import json
import boto3
import logging
from custom_encoder import CustomEncoder
logger = logging.getLogger()
logger.setLevel(logging.INFO)
dynamodbTableName = 'website_visitor_count'
dynamodb = boto3.resource('dynamodb')
table = dynamodb.Table(dynamodbTableName)
getMethod = 'GET'
putMethod = 'PUT'
healthPath = '/health'
visitorCountPath = '/visitor_count'
def lambda_handler(event, context):
logger.info(event)
httpMethod = event['httpMethod']
path = event['path']
if httpMethod == getMethod and path == healthPath:
response = buildResponse(200)
elif httpMethod == getMethod and path == visitorCountPath:
response = getVisitorCount('alexashworthdev')
elif httpMethod == putMethod and path == visitorCountPath:
response = updateVisitorCount('alexashworthdev')
else:
response = buildResponse(404, 'Not Found')
return response
def getVisitorCount(siteName):
try:
response = table.get_item(
Key={
'site_name': siteName
}
)
if 'Item' in response:
return buildResponse(200, response['Item'])
else:
return buildResponse(404, {'Message': 'site_name: %s not found' % siteName})
except:
return buildResponse(500)
def updateVisitorCount(siteName):
try:
response = table.update_item(
Key={
'site_name': siteName
},
UpdateExpression='SET visitor_count = visitor_count + :val',
ExpressionAttributeValues={':val': 1},
ReturnValues="UPDATED_NEW"
)
body = {
'Operation': 'UPDATE',
'Message': 'SUCCESS',
'UpdatedAttributes': response,
}
return buildResponse(200, body)
except:
return buildResponse(500)
def buildResponse(statusCode, body=None):
response = {
'statusCode': statusCode,
'headers': {
'Content-Type': 'application/json',
'Access-Control-Allow-Origin': '*'
}
}
if body is not None:
response['body'] = json.dumps(body, cls=CustomEncoder)
return response