JZ. JZ. - 2 months ago 28
Python Question

How to iterate over ResultProxy many times?

Suppose I execute the following query:

results = db.engine.execute(sql_query)


where it returns rows as expected:

>>> for record in results:
... print(record['path'])
...
Top.Collections.Pictures.Astronomy.Stars
Top.Collections.Pictures.Astronomy.Galaxies
Top.Collections.Pictures.Astronomy.Astronauts


When I try to iterate over it a second or third time the object is empty:

>>> for record in results:
... print(record['path'])
...
>>>


How can I save and reuse the ResultProxy to iterate over it many times?

Answer

You probably have an iterator object being returned, so once it's exhausted after iterating over it, you can't go over it again. Assuming your results are not extremely large, you can do:

results = db.engine.execute(sql_query) 
results = list(results)

That turns the iterator object into a list and you can iterate over it as many times as you would.