Skip to content

Instantly share code, notes, and snippets.

@jrothman
Last active July 25, 2020 13:42
Show Gist options
  • Save jrothman/6db19d5f3ab6c83c27f87212193a24aa to your computer and use it in GitHub Desktop.
Save jrothman/6db19d5f3ab6c83c27f87212193a24aa to your computer and use it in GitHub Desktop.
Testing DynamoDB ConditionExpression
import boto3
from boto3.dynamodb.conditions import Attr
test1 = {
"PK": "ITEM#1",
"SK": "v0#ACTIVE#20200724T07:08:09Z",
"data": "random stuff"
}
test2 = {
"PK": "ITEM#1",
"SK": "v0#ACTIVE#20200724T08:09:10Z",
"data": "something else"
}
dynamodb = boto3.resource('dynamodb', region_name='af-south-1')
#prep: create a table and name the Partitian Key = PK and the Sort Key = SK
db = dynamodb.Table("your-table-name")
db_status = db.table_status
try:
db.put_item(Item=test1, ConditionExpression=Attr("PK").ne(test1["PK"]))
except Exception as e:
print(f"Error: Could not insert test1. Is it a duplicate?: {str(e)}")
try:
db.put_item(Item=test2, ConditionExpression=Attr("PK").ne(test1["PK"]))
except Exception as e:
print(f"Error: Could not insert test2. Is it a duplicate?: {str(e)}")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment