How to iterate over ResultProxy many times?
<p>Suppose I execute the following query:</p>

<pre><code>results = db.engine.execute(sql_query)
</code></pre>

<p>where it returns rows as expected: </p>

<pre><code>&gt;&gt;&gt; for record in results:
...     print(record['path'])
... 
Top.Collections.Pictures.Astronomy.Stars
Top.Collections.Pictures.Astronomy.Galaxies
Top.Collections.Pictures.Astronomy.Astronauts
</code></pre>

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

<pre><code>&gt;&gt;&gt; for record in results:
...     print(record['path'])
...
&gt;&gt;&gt; 
</code></pre>

<p><strong>How can I save and reuse the ResultProxy to iterate over it many times?</strong></p>

<p>You probably have an <em>iterator</em> 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:</p>

<pre><code>results = db.engine.execute(sql_query) 
results = list(results)
</code></pre>

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

python sqlalchemy resultproxy