forked from aws-samples/serverless-test-samples
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.py
63 lines (49 loc) · 2.42 KB
/
app.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
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
# SPDX-License-Identifier: MIT-0
# Lambda Handler for the Python apigw-lambda-dynamodb example
# This handler accepts an id that represents a persons name, and creates a "Hello {Name}!" message.
# The id and name associated with the name is stored in a DynamoDB Table.
# Additionally, when a message is created, the lambda logs the "Hello {Name}!" message to DynamoDB with a timestamp.
# The DynamoDB Table used is passed as an environment variable "DYNAMODB_TABLE_NAME"
from os import environ
from datetime import datetime
import boto3
from aws_xray_sdk.core import patch_all
from aws_lambda_powertools.utilities.data_classes import APIGatewayProxyEvent
from aws_lambda_powertools.utilities.typing import LambdaContext
from aws_lambda_powertools.utilities.validation import validator
try:
from schemas import OUTPUT_SCHEMA
patch_all()
except:
from src.schemas import OUTPUT_SCHEMA
@validator(outbound_schema=OUTPUT_SCHEMA)
def lambda_handler(event: APIGatewayProxyEvent, context: LambdaContext) -> dict:
# Retrieve the table name from the environment, and create a boto3 Table object
dynamodb_table_name = environ["DYNAMODB_TABLE_NAME"]
dynamodb_resource = boto3.resource('dynamodb')
dynamodb_table = dynamodb_resource.Table(dynamodb_table_name)
print(f"Using DynamoDB Table {dynamodb_table_name}.")
# User id field is passed as a path parameter
id = event["pathParameters"]["id"]
# Retrieve the person's name from an id, and construct the message.
dynamodb_response = dynamodb_table.get_item(Key={"PK": f"{id}", "SK": "NAME#"})
# Does the person exist for this id?
if "Item" in dynamodb_response and "data" in dynamodb_response["Item"]:
person_name = dynamodb_response["Item"]["data"]
hello_message = f"Hello {person_name}!"
status_code = 200
else:
hello_message = f"NOTFOUND: Name Not Found for ID {id}"
status_code = 404
# Create a timestamp and log the message back to DynamoDB
datetime_stamp = "DT#" + datetime.now().strftime("%Y%m%dT%H%M%S.%f")
dynamodb_table.put_item(Item={'PK' : id,
'SK' : datetime_stamp,
'data': hello_message})
# Log and return
print(f"Message: {hello_message} - {datetime_stamp}")
return {
"statusCode": status_code,
"body": hello_message
}