I am creating a pager that returns documents from an Apache CouchDB map function from python-couchdb. This generator expression is working well, until it hits the max recursion depth. How can it be improved to move to iteration, rather than recursion?
def page(db, view_name, limit, include_docs=True, **opts):
"""
`page` goes returns all documents of CouchDB map functions. It accepts
all options that `couchdb.Database.view` does, however `include_docs`
should be omitted, because this will interfere with things.
>>> import couchdb
>>> db = couchdb.Server()['database']
>>> for doc in page(db, '_all_docs', 100):
>>> doc
#etc etc
>>> del db['database']
Notes on implementation:
- `last_doc` is assigned on every loop, because there doesn't seem to
be an easy way to know if something is the last item in the iteration.
"""
last_doc = None
for row in db.view(view_name,
limit=limit+1,
include_docs=include_docs,
**opts):
last_doc = row.key, row.id
yield row.doc
if last_doc:
for doc in page(db, view_name, limit,
inc_docs=inc_docs,
startkey=last_doc[0],
startkey_docid=last_doc[1]):
yield doc