Skip to content

Commit

Permalink
Merge pull request #485 from idoshr/pagigation
Browse files Browse the repository at this point in the history
Improved: Pagination performance
  • Loading branch information
insspb committed Jul 23, 2022
2 parents c1a4edd + 19a381b commit 67e6388
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 7 deletions.
20 changes: 13 additions & 7 deletions flask_mongoengine/pagination.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,14 +16,20 @@ def __init__(self, iterable, page, per_page):
self.iterable = iterable
self.page = page
self.per_page = per_page
self.total = len(iterable)

start_index = (page - 1) * per_page
end_index = page * per_page

self.items = iterable[start_index:end_index]
if isinstance(self.items, QuerySet):
self.items = self.items.select_related()
if isinstance(self.iterable, QuerySet):
self.total = iterable.count()
self.items = (
self.iterable.skip(self.per_page * (self.page - 1))
.limit(self.per_page)
.select_related()
)
else:
start_index = (page - 1) * per_page
end_index = page * per_page

self.total = len(iterable)
self.items = iterable[start_index:end_index]
if not self.items and page != 1:
abort(404)

Expand Down
6 changes: 6 additions & 0 deletions tests/test_pagination.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,12 @@ def test_queryset_paginator(app, todo):
paginator = Pagination(Todo.objects, 1, 10)
_test_paginator(paginator)

for page in range(1, 10):
for index, todo in enumerate(
Todo.objects.paginate(page=page, per_page=5).items
):
assert todo.title == f"post: {(page-1) * 5 + index}"


def test_paginate_plain_list():
with pytest.raises(NotFound):
Expand Down

0 comments on commit 67e6388

Please sign in to comment.