Skip to content

Instantly share code, notes, and snippets.

@velotiotech
Created June 17, 2020 09:41
Show Gist options
  • Save velotiotech/834c0e6b7d66c27c918074676e0b4808 to your computer and use it in GitHub Desktop.
Save velotiotech/834c0e6b7d66c27c918074676e0b4808 to your computer and use it in GitHub Desktop.
DynamoDB Example
from __future__ import print_function # Python 2/3 compatibility
import boto3
import json
import decimal
from boto3.dynamodb.conditions import Key, Attr
from botocore.exceptions import ClientError
# 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)
dynamodb = boto3.resource("dynamodb", region_name='us-west-2', endpoint_url="http://localhost:8000")
table = dynamodb.Table('Movies')
title = "The Big New Movie"
year = 2015
try:
response = table.get_item(
Key={
'year': year,
'title': title
}
)
except ClientError as e:
print(e.response['Error']['Message'])
else:
item = response['Item']
print("GetItem succeeded:")
print(json.dumps(item, indent=4, cls=DecimalEncoder))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment