using WebHelpers paginate with MongoDB

using WebHelpers paginate with MongoDB

This is a simple little class wrapping the mongodb cursor class in order to implement the few methods required by the paginate module.

CursorWrapper class

Copy the following to your library and import it where you intent to use it.

class CursorWrapper(object):

    """Wraps the MongoDB cursor to work with the paginate module."""

    def __init__(self, cur):
        self.cur = cur

    __iter__ = lambda self: self.cur.__iter__()
    __len__ = lambda self: self.cur.count()
    __getitem__ = lambda self, key: self.cur.__getitem__(key)


You can then use this this way, replacing your SQLAlchemy query or list by the collection cursor wrapped in the CursorWrapper:

cursor = mycollection.find()
page = Page(CursorWrapper(cursor), items_per_page=20)
Bertrand Janin <> · Powered by Python & Debian GNU/Linux