Last active
July 12, 2018 19:03
-
-
Save apackeer/55b38df8227179365241205ed51d1511 to your computer and use it in GitHub Desktop.
Lambda Dynamo Demo
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from __future__ import print_function # Python 2/3 compatibility | |
import boto3 | |
import json | |
import decimal | |
import time | |
# Helper class to convert a DynamoDB item to JSON. | |
class DecimalEncoder(json.JSONEncoder): | |
def default(self, o): | |
if isinstance(o, decimal.Decimal): | |
if o % 1 > 0: | |
return float(o) | |
else: | |
return int(o) | |
return super(DecimalEncoder, self).default(o) | |
def lambda_handler(event, context): | |
print("event: " + json.dumps(event)) | |
print("Log stream name:", context.log_stream_name) | |
print("Log group name:", context.log_group_name) | |
print("Request ID:",context.aws_request_id) | |
print("Mem. limits(MB):", context.memory_limit_in_mb) | |
# Code will execute quickly, so we add a 1 second intentional delay so you can see that in time remaining value. | |
time.sleep(1) | |
print("Time remaining (MS):", context.get_remaining_time_in_millis()) | |
return "OK" | |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from __future__ import print_function # Python 2/3 compatibility | |
import boto3 | |
import json | |
import decimal | |
import time | |
# Helper class to convert a DynamoDB item to JSON. | |
class DecimalEncoder(json.JSONEncoder): | |
def default(self, o): | |
if isinstance(o, decimal.Decimal): | |
if o % 1 > 0: | |
return float(o) | |
else: | |
return int(o) | |
return super(DecimalEncoder, self).default(o) | |
def lambda_handler(event, context): | |
print("event: " + json.dumps(event)) | |
dynamodb = boto3.resource('dynamodb') | |
table = dynamodb.Table('LambdaDemo') | |
id = event['id'] | |
balance = event['balance'] | |
response = table.put_item( | |
Item={ | |
'id': id, | |
'balance': balance | |
} | |
) | |
print("PutItem succeeded:") | |
print(json.dumps(response, indent=4, cls=DecimalEncoder)) | |
return "OK" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
curl -H 'Content-Type: application/json' -X PUT -d '{"id":"Bruce Banner","balance":300}' https://jhn8j1zr5d.execute-api.ap-southeast-2.amazonaws.com/Test/users