@@ -86,7 +86,6 @@ def _to_epoch_float(dt):
8686 "array" : json .dumps ,
8787}
8888
89-
9089DESERIALIZE_MAP = {
9190 "number" : float ,
9291 "boolean" : bool ,
@@ -95,6 +94,11 @@ def _to_epoch_float(dt):
9594}
9695
9796
97+ def chunk_list (lst , size ):
98+ for i in range (0 , len (lst ), size ):
99+ yield lst [i :i + size ]
100+
101+
98102def index_definition (index_name , keys , gsi = False ):
99103 schema = {
100104 "IndexName" : index_name ,
@@ -112,7 +116,7 @@ def index_definition(index_name, keys, gsi=False):
112116
113117class DynamoSerializer :
114118 def __init__ (self , schema ):
115- self .properties = schema [ "properties" ]
119+ self .properties = schema . get ( "properties" )
116120 self .definitions = schema .get ("definitions" )
117121
118122 def _get_type_possibilities (self , field_name ) -> Set [tuple ]:
@@ -409,3 +413,28 @@ def save(self, item, condition: Optional[Rule] = None) -> bool:
409413
410414 def delete (self , key ):
411415 self .get_table ().delete_item (Key = self ._key_param_to_dict (key ))
416+
417+ def batch_save (self , items : list ) -> dict :
418+ """
419+ This function is to write multiple records in to dynamodb and returns unprocessed records in dict
420+ if something gone wrong with the record.Currently, batch_write is not supporting ConditionExpression
421+ Refer docs:
422+ https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/dynamodb/client/batch_write_item.html
423+ """
424+ # Prepare the batch write requests
425+ request_items = {self .table_name : []}
426+
427+ # chunk list for size limit of 25 items to write using this batch_write operation refer below.
428+ # https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/dynamodb/client/batch_write_item.html#:~:text=The%20BatchWriteItem%20operation,Data%20Types.
429+ for chunk in chunk_list (items , 25 ):
430+ serialized_items = [self .serializer .serialize_record (item .dict (by_alias = True )) for item in chunk ]
431+ for serialized_item in serialized_items :
432+ request_items [self .table_name ].append ({"PutRequest" : {"Item" : serialized_item }})
433+ try :
434+ response = self .dynamodb .batch_write_item (RequestItems = request_items )
435+ except ClientError as e :
436+ raise e
437+ except (ValueError , TypeError , KeyError ) as ex :
438+ raise ex
439+ unprocessed_items = response .get ("UnprocessedItems" , {})
440+ return unprocessed_items
0 commit comments