@@ -92,7 +92,6 @@ def _to_epoch_decimal(dt: datetime) -> Decimal:
9292 "array" : json .dumps ,
9393}
9494
95-
9695DESERIALIZE_MAP = {
9796 "number" : float ,
9897 "boolean" : bool ,
@@ -101,6 +100,11 @@ def _to_epoch_decimal(dt: datetime) -> Decimal:
101100}
102101
103102
103+ def chunk_list (lst , size ):
104+ for i in range (0 , len (lst ), size ):
105+ yield lst [i :i + size ]
106+
107+
104108def index_definition (index_name , keys , gsi = False ):
105109 schema = {
106110 "IndexName" : index_name ,
@@ -118,7 +122,7 @@ def index_definition(index_name, keys, gsi=False):
118122
119123class DynamoSerializer :
120124 def __init__ (self , schema , ttl_field = None ):
121- self .properties = schema [ "properties" ]
125+ self .properties = schema . get ( "properties" )
122126 self .definitions = schema .get ("definitions" )
123127 self .ttl_field = ttl_field
124128
@@ -420,3 +424,28 @@ def save(self, item, condition: Optional[Rule] = None) -> bool:
420424
421425 def delete (self , key ):
422426 self .get_table ().delete_item (Key = self ._key_param_to_dict (key ))
427+
428+ def batch_save (self , items : list ) -> dict :
429+ """
430+ This function is to write multiple records in to dynamodb and returns unprocessed records in dict
431+ if something gone wrong with the record.Currently, batch_write is not supporting ConditionExpression
432+ Refer docs:
433+ https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/dynamodb/client/batch_write_item.html
434+ """
435+ # Prepare the batch write requests
436+ request_items = {self .table_name : []}
437+
438+ # chunk list for size limit of 25 items to write using this batch_write operation refer below.
439+ # https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/dynamodb/client/batch_write_item.html#:~:text=The%20BatchWriteItem%20operation,Data%20Types.
440+ for chunk in chunk_list (items , 25 ):
441+ serialized_items = [self .serializer .serialize_record (item .dict (by_alias = True )) for item in chunk ]
442+ for serialized_item in serialized_items :
443+ request_items [self .table_name ].append ({"PutRequest" : {"Item" : serialized_item }})
444+ try :
445+ response = self .dynamodb .batch_write_item (RequestItems = request_items )
446+ except ClientError as e :
447+ raise e
448+ except (ValueError , TypeError , KeyError ) as ex :
449+ raise ex
450+ unprocessed_items = response .get ("UnprocessedItems" , {})
451+ return unprocessed_items
0 commit comments