In this exercise you will see the TTL feature in action. Code here is using the local DynamoDB table but you may very well try it with a table on AWS cloud.
aws dynamodb create-table \
--table-name TTLTest \
--attribute-definitions '[
{
"AttributeName": "PK",
"AttributeType": "S"
}
]' \
--key-schema '[
{
"AttributeName": "PK",
"KeyType": "HASH"
}
]' \
--billing-mode PAY_PER_REQUEST \
--endpoint-url http://localhost:8000
aws dynamodb update-time-to-live \
--table-name TTLTest \
--time-to-live-specification 'Enabled=true,AttributeName=ttl' \
--endpoint-url http://localhost:8000
import boto3
import time
from datetime import datetime
TABLE_NAME = "TTLTest"
# Time after which item will expire
EXPIRE_TTL = 10
# Code sleeps and checks existence of item
SLEEP_TIME = 5
# Connect to localhost
client = boto3.client("dynamodb", region_name="localhost", endpoint_url="http://localhost:8000", aws_access_key_id="access_key_id", aws_secret_access_key="secret_access_key")
ttl = int(time.time()) + EXPIRE_TTL
# Add an item
PK = str(datetime.now()).replace(" ","-")
response = client.put_item(
TableName=TABLE_NAME,
Item={
"PK": {"S": PK},
"ttl": {"N": str(ttl)},
},
)
print(f"Added item PK = {PK}")
# Continuously check for the item in table
start_time = int(time.time())
while True:
print('.', end='', flush=True),
response = client.get_item(
TableName=TABLE_NAME,
Key={
"PK": {"S": PK},
},
)
time.sleep(SLEEP_TIME)
if 'Item' not in response.keys() :
break
time_taken = int(time.time()) - start_time
print('Item expired in {} seconds'.format(time_taken))
python ttl/put-and-wait-for-expiry.py
aws dynamodb delete-table \
--table-name TTLTest \
--endpoint-url http://localhost:8000