Created
March 23, 2017 04:44
-
-
Save pilgrim2go/4aac81897ca80e90fd43577bdaa1eed9 to your computer and use it in GitHub Desktop.
Using ExpressionAttributeNames to alias DynamoDB reserved keywords
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 | |
import boto3 | |
import json | |
import decimal | |
from boto3.dynamodb.conditions import Key, Attr | |
from botocore.exceptions import ClientError | |
from pprint import pprint | |
# Helper Class to convert a DDB 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-east-1') | |
table = dynamodb.Table('test-table') | |
# Adding movie: 2013 This Is the End | |
item_type = 'tenant' | |
id = 'test1oct25' | |
def test_get(): | |
try: | |
response = table.get_item( | |
Key = { | |
'id': id, | |
'item-type': item_type | |
} | |
) | |
except ClientError as e: | |
print(e.response['Error']['Message']) | |
else: | |
item = response['Item'] | |
print('GetItem succeeded:') | |
print(json.dumps(item, indent=4, cls=DecimalEncoder)) | |
def test_update(): | |
try: | |
response = table.update_item( | |
Key = { | |
'id': id, | |
'item-type': item_type | |
}, | |
UpdateExpression="set #d.currency = :c", | |
ExpressionAttributeValues = { | |
':c': 'VND', | |
}, | |
ExpressionAttributeNames = { | |
'#d': 'data' | |
}, | |
ReturnValues="UPDATED_NEW" | |
) | |
except ClientError as e: | |
print(e.response['Error']['Message']) | |
else: | |
print('UpdateItem succeeded:') | |
print(json.dumps(response, indent=4, cls=DecimalEncoder)) | |
test_update() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment