This program writes up to 25 items at a time to a DynamoDB table named 'Books'. If some items are not processed, it retries them until all are written.
import boto3
from botocore.exceptions import ClientError
# Create DynamoDB client
client = boto3.client('dynamodb')
def batch_write_with_retries(table_name, items):
max_batch_size = 25
unprocessed_items = []
# Split items into batches of 25
for i in range(0, len(items), max_batch_size):
batch = items[i:i+max_batch_size]
request_items = {table_name: [{'PutRequest': {'Item': item}} for item in batch]}
while True:
response = client.batch_write_item(RequestItems=request_items)
unprocessed = response.get('UnprocessedItems', {})
if not unprocessed or not unprocessed.get(table_name):
break # All items processed
# Retry unprocessed items
request_items = unprocessed
print(f"All items written to {table_name} with retries if needed.")
# Example items to write
items_to_write = [
{'ISBN': {'S': '001'}, 'Title': {'S': 'Book One'}},
{'ISBN': {'S': '002'}, 'Title': {'S': 'Book Two'}},
{'ISBN': {'S': '003'}, 'Title': {'S': 'Book Three'}}
]
print("Before batch write")
batch_write_with_retries('Books', items_to_write)
print("After batch write")