Skip to content

Commit

Permalink
(joe) enable ttl
Browse files Browse the repository at this point in the history
  • Loading branch information
jbylund committed Feb 14, 2024
1 parent 9fcc4e2 commit 8ea766d
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 1 deletion.
13 changes: 12 additions & 1 deletion src/dynamodict/dynamodict.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
import pickle
import sys
import time
from decimal import Decimal

# site imports
import boto3
Expand Down Expand Up @@ -67,6 +68,15 @@ def __init__(self, table_name, read_units=None, write_units=None, ttl=None):
# check if it's a table does not exist error
self.create_table(read_units=read_units, write_units=write_units)
self.table.wait_until_exists()
if self.ttl:
# ensure the table has ttl enabled and pointing to the right attribute
self.client.update_time_to_live(
TableName=self.table_name,
TimeToLiveSpecification={
"Enabled": True,
"AttributeName": TTL_ATTR_NAME,
},
)

def create_table(self, read_units=None, write_units=None):
"""create a table in case it doesn't exist"""
Expand Down Expand Up @@ -108,7 +118,8 @@ def __setitem__(self, key, value):
VAL_ATTR_NAME: serialize(value),
}
if self.ttl:
to_put[TTL_ATTR_NAME] = time.time() + self.ttl
expiry = time.time() + self.ttl
to_put[TTL_ATTR_NAME] = Decimal(expiry)
for i in range(5):
try:
self.table.put_item(Item=to_put)
Expand Down
7 changes: 7 additions & 0 deletions tests/test_dynamodictionary.py
Original file line number Diff line number Diff line change
Expand Up @@ -155,3 +155,10 @@ def test_values(self):
values = self.mytable.values()
assert isinstance(values, list)
assert sorted(values) == sorted(keys)

def test_ttl(self):
try:
table_with_ttl = dynamodict.DynamoDictionary(randstr(), ttl=10)
table_with_ttl["foo"] = "bar"
finally:
table_with_ttl.client.delete_table(TableName=table_with_ttl.table_name)

0 comments on commit 8ea766d

Please sign in to comment.