from typing import Callable from django.core.paginator import Page, Paginator from django.shortcuts import redirect from lemoncurry.middleware import ResponseException def paginate(queryset, reverse: Callable[[int], str], page: int | None) -> Page: def redirect_to_page(i: int): raise ResponseException(redirect(reverse(i))) def reversible(p: Page) -> Page: p.reverse = reverse return p paginator = Paginator(queryset, 10) # If no page number was specified, return page one. if page is None: return reversible(paginator.page(1)) # If the first page was explicitly requested, or the page number was negative, redirect to page one with no URL suffix. if page <= 1: redirect_to_page(1) # If the page requested is larger than the last page, then redirect to the last page. if page > paginator.num_pages: redirect_to_page(paginator.num_pages) # Just return the current page! Hooray! return reversible(paginator.page(page))