Skip to content

Commit b010ebf

Browse files
author
Tom McCarthy
committed
feat: alter DynamoDB persistence class to set the table attribute lazily, making it easier to test.
1 parent 68e2c8e commit b010ebf

File tree

1 file changed

+24
-5
lines changed
  • aws_lambda_powertools/utilities/idempotency/persistence

1 file changed

+24
-5
lines changed

aws_lambda_powertools/utilities/idempotency/persistence/dynamodb.py

Lines changed: 24 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -62,18 +62,37 @@ def __init__(
6262
>>> return {"StatusCode": 200}
6363
"""
6464

65-
boto_config = boto_config or Config()
66-
session = boto3_session or boto3.session.Session()
67-
self._ddb_resource = session.resource("dynamodb", config=boto_config)
65+
self._boto_config = boto_config or Config()
66+
self._boto3_session = boto3_session or boto3.session.Session()
67+
68+
self._table = None
6869
self.table_name = table_name
69-
self.table = self._ddb_resource.Table(self.table_name)
7070
self.key_attr = key_attr
7171
self.expiry_attr = expiry_attr
7272
self.status_attr = status_attr
7373
self.data_attr = data_attr
7474
self.validation_key_attr = validation_key_attr
7575
super(DynamoDBPersistenceLayer, self).__init__()
7676

77+
@property
78+
def table(self):
79+
"""
80+
Caching property to store boto3 dynamodb Table resource
81+
82+
"""
83+
if self._table:
84+
return self._table
85+
ddb_resource = self._boto3_session.resource("dynamodb", config=self._boto_config)
86+
self._table = ddb_resource.Table(self.table_name)
87+
return self._table
88+
89+
@table.setter
90+
def table(self, table):
91+
"""
92+
Allow table instance variable to be set directly, primarily for use in tests
93+
"""
94+
self._table = table
95+
7796
def _item_to_data_record(self, item: Dict[str, Any]) -> DataRecord:
7897
"""
7998
Translate raw item records from DynamoDB to DataRecord
@@ -125,7 +144,7 @@ def _put_record(self, data_record: DataRecord) -> None:
125144
ExpressionAttributeNames={"#id": self.key_attr, "#now": self.expiry_attr},
126145
ExpressionAttributeValues={":now": int(now.timestamp())},
127146
)
128-
except self._ddb_resource.meta.client.exceptions.ConditionalCheckFailedException:
147+
except self.table.meta.client.exceptions.ConditionalCheckFailedException:
129148
logger.debug(f"Failed to put record for already existing idempotency key: {data_record.idempotency_key}")
130149
raise IdempotencyItemAlreadyExistsError
131150

0 commit comments

Comments
 (0)