Skip to content

Instantly share code, notes, and snippets.

@snahor
Last active January 1, 2016 04:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save snahor/8091563 to your computer and use it in GitHub Desktop.
Save snahor/8091563 to your computer and use it in GitHub Desktop.
from math import ceil
from mongoengine.queryset import QuerySet
__all__ = ('paginate',)
def paginate(page=1,
total=0,
adjacents=2,
per_page=1,
iterable=None):
"""
>> paginate(page=7, total=200, adjacents=2, per_page=4)
{'items': None,
'page': 7,
'pages': [5, 6, 7, 8, 9],
'total': 200,
'total_pages': 50}
>> paginate(page=50, total=200, adjacents=2, per_page=4)
{'items': None,
'page': 50,
'pages': [46, 47, 48, 49, 50],
'total': 200,
'total_pages': 50}
>> paginate(page=50, total=200, adjacents=3, per_page=4)
{'items': None,
'page': 50,
'pages': [44, 45, 46, 47, 48, 49, 50],
'total': 200,
'total_pages': 50}
"""
try:
page = int(page) or 1
except (ValueError, TypeError):
page = 1
items = None
if iterable:
if isinstance(iterable, QuerySet):
total = iterable.count()
else:
total = len(iterable)
items = iterable[(page - 1) * per_page:page * per_page]
total_pages = int(ceil(total / (per_page * 1.0)))
if page > total_pages:
pages = []
elif total_pages <= 2 * adjacents:
pages = range(1, total_pages + 1)
else:
if page <= adjacents:
start = 1
else:
if total_pages - page < adjacents:
start = total_pages - 2 * adjacents
else:
start = page - adjacents
increment = 2 * adjacents + 1
pages = range(start, start + increment)
return {
'page': page,
'pages': pages,
'total': total,
'total_pages': total_pages,
'items': items,
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment