This answer on StackExchange served me well:
Expired queries and appengine
I had to slightly modify it to work for me:
def loop_over_objects_in_batches(batch_size, object_class, callback):
num_els = object_class.count()
num_loops = num_els / batch_size
remainder = num_els - num_loops * batch_size
logging.info("Calling batched loop with batch_size: %d, num_els: %s, num_loops: %s, remainder: %s, object_class: %s, callback: %s," % (batch_size, num_els, num_loops, remainder, object_class, callback))
offset = 0
while offset < num_loops * batch_size:
logging.info("Processing batch (%d:%d)" % (offset, offset+batch_size))
query = object_class[offset:offset + batch_size]
for q in query:
callback(q)
offset = offset + batch_size
if remainder:
logging.info("Processing remainder batch (%d:%d)" % (offset, num_els))
query = object_class[offset:num_els]
for q in query:
callback(q)