classRecordCollection(object): """A set of excellent Records from a query.""" def__init__(self, rows): self._rows = rows self._all_rows = [] self.pending = True
def__iter__(self): """Iterate over all rows, consuming the underlying generator only when necessary.""" i = 0 whileTrue: # Other code may have iterated between yields, # so always check the cache. if i < len(self): yield self[i] else: # Throws StopIteration when done. # Prevent StopIteration bubbling from generator, following https://www.python.org/dev/peps/pep-0479/ try: yieldnext(self) except StopIteration: return i += 1
defnext(self): return self.__next__()
def__next__(self): try: nextrow = next(self._rows) self._all_rows.append(nextrow) return nextrow except StopIteration: self.pending = False raise StopIteration('RecordCollection contains no more rows.')
rows = self._all_rows[key] if is_int: return rows[0] else: return RecordCollection(iter(rows))
def__len__(self): returnlen(self._all_rows)
defexport(self, format, **kwargs): """Export the RecordCollection to a given format (courtesy of Tablib).""" return self.dataset.export(format, **kwargs)
defall(self, as_dict=False, as_ordereddict=False): """Returns a list of all rows for the RecordCollection. If they haven't been fetched yet, consume the iterator and cache the results."""
# By calling list it calls the __iter__ method rows = list(self)
if as_dict: return [r.as_dict() for r in rows] elif as_ordereddict: return [r.as_dict(ordered=True) for r in rows]