IC Improve Code Recipes

Recipe 16.4 · Python

A Reusable Paging Model for Grids

The Python listings are conversions of the book's C# code to Python 3.12. Each file's header says what it needs to run. The explanations were written for the C# version, so some names in the text refer to .NET.

Problem

Grids page through data in almost every screen. The Web Forms version loads every row into a DataSet, binds it to a GridView with AllowPaging="true", and lets the control throw away all but 25 rows. On a table with 400,000 rows that's slow for the user and expensive for the database, and the pager code is copied into every screen.

The way it's often written

Anti-pattern: shown so you can recognize it. Don't copy this one.

Requirements: Python 3.12+. Install: pip install pyodbc · Needs at run time: SQL Server + Microsoft ODBC Driver 18 for SQL Server. The module loads without them; calling the code does not work without them.

Python Grid binding that loads every invoice and pages in memory (p362_r16_4_load_all_page_in_memory_before.py)
"""Grid binding that loads every invoice and pages in memory

Source: ImproveCode, Chapter 16, Recipe 16.4 "A Reusable Paging Model for Grids"
Section: The way it's often written
Book page: 362  -- original C# listing
Converted from C# to Python.
ANTI-PATTERN: kept deliberately faithful to the C# 'not to copy' example; do not use.
SqlHelper.ExecuteDataset becomes pyodbc fetchall(); the GridView becomes a simple grid
object whose data_bind slices the full result set in memory.
"""

from typing import Any

import pyodbc


class InvoicesPage:
    def __init__(self, conn_string: str, gv_invoices: Any) -> None:
        self.conn_string = conn_string
        self.gv_invoices = gv_invoices

    # Not to copy: load everything, page in memory.
    def bind_grid(self) -> None:
        with pyodbc.connect(self.conn_string) as conn:
            ds = conn.cursor().execute("SELECT * FROM Invoice").fetchall()
        self.gv_invoices.data_source = ds
        self.gv_invoices.data_bind()

    def gv_invoices_page_index_changing(self, new_page_index: int) -> None:
        self.gv_invoices.page_index = new_page_index
        self.bind_grid()  # runs the query again

The improved recipe

Links keep the other query-string values (filters, sort) and replace only the page:

The controller asks a query service for one page:

The query behind SearchAsync uses OFFSET/FETCH (Chapter 2):

SQL
SELECT COUNT(*) FROM dbo.Invoice WHERE CustomerId = @CustomerId;

SELECT InvoiceId, InvoiceNumber, InvoiceDate, Total
FROM dbo.Invoice
WHERE CustomerId = @CustomerId
ORDER BY InvoiceDate DESC, InvoiceId DESC
OFFSET @Skip ROWS FETCH NEXT @PageSize ROWS ONLY;

And one partial view renders the pager for every grid:

Text
@* Views/Shared/_Pager.cshtml *@
@using ImproveCode.Web.Paging
@model IPagedResult

@if (Model.TotalPages > 1)
{
    <nav aria-label="Pages">
        <ul class="pagination">
            @if (Model.HasPrevious)
            {
                <li class="page-item">
                    <a class="page-link" href="@PageLinks.Url(
                        Context.Request, Model.Page - 1)">Previous</a>
                </li>
            }
            @foreach (int? number in Model.PageNumbers())
            {
                if (number is int n)
                {
                    <li class="page-item @(n == Model.Page
                        ? "active" : "")">
                        <a class="page-link" href="@PageLinks.Url(
                            Context.Request, n)">@n</a>
                    </li>
                }
                else
                {
                    <li class="page-item disabled">
                        <span class="page-link">&hellip;</span>
                    </li>
                }
            }
            @if (Model.HasNext)
            {
                <li class="page-item">
                    <a class="page-link" href="@PageLinks.Url(
                        Context.Request, Model.Page + 1)">Next</a>
                </li>
            }
        </ul>
    </nav>
    <p>Showing @Model.FirstItem to @Model.LastItem
        of @Model.TotalCount</p>
}

In any grid view: @await Html.PartialAsync("_Pager", Model).

Requirements: Python 3.12+. Install: pip install sqlalchemy greenlet

Python Reusable paging model: page request, paged result, page-number window, query paging (p362_r16_4_paged_result_and_page_window.py)
"""Reusable paging model: page request, paged result, page-number window, query paging

Source: ImproveCode, Chapter 16, Recipe 16.4 "A Reusable Paging Model for Grids"
Section: The improved recipe
Book page: 362-364  -- original C# listing
Converted from C# to Python.
IQueryable paging becomes SQLAlchemy 2.0: a COUNT over the ordered Select as a subquery,
then OFFSET/LIMIT. IPagedResult becomes a Protocol; records become frozen dataclasses.
"""

from __future__ import annotations

from dataclasses import dataclass, field
from typing import Any, ClassVar, Protocol

from sqlalchemy import Select, func, select
from sqlalchemy.orm import Session

_INT_MAX = 2**31 - 1


def _clamp(value: int, low: int, high: int) -> int:
    return max(low, min(value, high))


@dataclass(frozen=True, init=False)
class PageRequest:
    DEFAULT_PAGE_SIZE: ClassVar[int] = 25
    MAX_PAGE_SIZE: ClassVar[int] = 200

    page: int
    page_size: int

    def __init__(self, page: int, page_size: int = 25) -> None:
        object.__setattr__(self, "page", _clamp(page, 1, _INT_MAX // self.MAX_PAGE_SIZE))
        object.__setattr__(self, "page_size", _clamp(page_size, 1, self.MAX_PAGE_SIZE))

    @property
    def skip(self) -> int:
        return (self.page - 1) * self.page_size


class IPagedResult(Protocol):
    @property
    def page(self) -> int: ...
    @property
    def total_count(self) -> int: ...
    @property
    def total_pages(self) -> int: ...
    @property
    def has_previous(self) -> bool: ...
    @property
    def has_next(self) -> bool: ...
    @property
    def first_item(self) -> int: ...
    @property
    def last_item(self) -> int: ...
    def page_numbers(self, window: int = 7) -> list[int | None]: ...


@dataclass(frozen=True)
class PagedResult[T]:
    items: list[T]
    total_count: int
    request: PageRequest = field(repr=False)

    def __post_init__(self) -> None:
        object.__setattr__(self, "total_count", max(0, self.total_count))

    @property
    def page(self) -> int:
        return self.request.page

    @property
    def page_size(self) -> int:
        return self.request.page_size

    @property
    def total_pages(self) -> int:
        return (self.total_count + self.page_size - 1) // self.page_size

    @property
    def has_previous(self) -> bool:
        return self.page > 1

    @property
    def has_next(self) -> bool:
        return self.page < self.total_pages

    @property
    def first_item(self) -> int:
        return 0 if len(self.items) == 0 else ((self.page - 1) * self.page_size) + 1

    @property
    def last_item(self) -> int:
        return 0 if len(self.items) == 0 else self.first_item + len(self.items) - 1

    def page_numbers(self, window: int = 7) -> list[int | None]:
        return compute_page_window(self.page, self.total_pages, window)


# Page numbers to show; None marks a gap ("...").
def compute_page_window(current: int, total_pages: int, window: int = 7) -> list[int | None]:
    if window < 5:
        raise ValueError("window must be at least 5.")
    pages: list[int | None] = []
    if total_pages <= window:
        pages.extend(range(1, total_pages + 1))
        return pages

    current = _clamp(current, 1, total_pages)
    inner = window - 2
    start = max(2, current - (inner // 2))
    end = start + inner - 1
    if end > total_pages - 1:
        end = total_pages - 1
        start = end - inner + 1

    pages.append(1)
    if start > 2:
        pages.append(None)
        start += 1

    gap_at_end = end < total_pages - 1
    if gap_at_end:
        end -= 1

    pages.extend(range(start, end + 1))

    if gap_at_end:
        pages.append(None)

    pages.append(total_pages)
    return pages


# The query must be ordered before paging.
def to_paged_result(session: Session, query: Select[Any], request: PageRequest) -> PagedResult[Any]:
    total = session.scalar(select(func.count()).select_from(query.order_by(None).subquery())) or 0
    items = list(session.scalars(query.offset(request.skip).limit(request.page_size)))
    return PagedResult(items, total, request)

Requirements: Python 3.12+. Install: pip install fastapi

Python Invoices list endpoint: permission check, session customer, server-side paging (p365_r16_4_invoices_paged_endpoint.py)
"""Invoices list endpoint: permission check, session customer, server-side paging

Source: ImproveCode, Chapter 16, Recipe 16.4 "A Reusable Paging Model for Grids"
Section: The improved recipe
Book page: 365-366  -- original C# listing
Converted from C# to Python.
The MVC controller becomes a FastAPI router rendering a Jinja2 template; IInvoiceQueries
becomes an async Protocol injected via Depends. CancellationToken is dropped: asyncio
cancels the request task directly.
"""

from dataclasses import dataclass
from datetime import date
from decimal import Decimal
from typing import Annotated, Protocol

from fastapi import APIRouter, Depends, Request, status
from fastapi.responses import RedirectResponse, Response
from fastapi.templating import Jinja2Templates

from p351_r16_1_require_permission_dependency import RequirePermission
from p360_r16_3_session_middleware_setup import UserSessionDep
from p362_r16_4_paged_result_and_page_window import PagedResult, PageRequest


@dataclass(frozen=True)
class InvoiceRow:
    invoice_id: int
    invoice_number: str
    invoice_date: date
    total: Decimal


class InvoiceQueries(Protocol):
    async def search(self, customer_id: int, page: PageRequest) -> PagedResult[InvoiceRow]: ...


def get_invoice_queries(request: Request) -> InvoiceQueries:
    return request.app.state.invoice_queries


router = APIRouter()
templates = Jinja2Templates(directory="templates")


@router.get(
    "/invoices",
    name="invoices_index",
    dependencies=[Depends(RequirePermission("Invoices.View"))],
)
async def index(
    request: Request,
    invoices: Annotated[InvoiceQueries, Depends(get_invoice_queries)],
    user_session: UserSessionDep,
    page: int = 1,
    size: int = PageRequest.DEFAULT_PAGE_SIZE,
) -> Response:
    customer_id = user_session.selected_customer_id
    if customer_id is None:
        return RedirectResponse(request.url_for("customers_select"), status.HTTP_302_FOUND)

    result = await invoices.search(customer_id, PageRequest(page, size))
    return templates.TemplateResponse(request, "invoices/index.html", {"model": result})

Requirements: Python 3.12+. Install: pip install starlette

Python Build a pager link that keeps the current query string and replaces page (p365_r16_4_page_link_url_builder.py)
"""Build a pager link that keeps the current query string and replaces page

Source: ImproveCode, Chapter 16, Recipe 16.4 "A Reusable Paging Model for Grids"
Section: The improved recipe
Book page: 365  -- original C# listing
Converted from C# to Python.
HttpRequest/QueryHelpers become Starlette's Request.query_params and urllib.parse.urlencode;
PathBase maps to the ASGI root_path.
"""

from urllib.parse import urlencode

from starlette.requests import Request


def page_url(request: Request, page: int) -> str:
    query = [
        (key, value)
        for key, value in request.query_params.multi_items()
        if key.casefold() != "page"
    ]
    query.append(("page", str(page)))

    path = request.scope.get("root_path", "") + request.url.path
    return f"{path}?{urlencode(query)}"

How it works

PageRequest cleans up input once. A page of 0, -3 or 999999999 and a page size of 100000 from a hand-edited URL are clamped to safe values, so a user can't ask the database for a million rows. Skip is computed in one place, which is where off-by-one errors used to hide.

PagedResult<T> carries one page of items plus the numbers the pager needs. TotalPages uses long arithmetic, so a large total doesn't overflow. FirstItem and LastItem produce "Showing 26 to 50 of 1,203" without anyone doing arithmetic in a view.

PageWindow.Compute produces a fixed-width list such as 1 … 9 10 11 … 20: always the first and last page, the current page with neighbors, and null where a gap goes. The pager's width doesn't jump as the user clicks, and the logic is a pure function you can unit test.

The database does the paging. The archive shows how rare that has been: about 692 SQL files page with ROW_NUMBER() OVER (10 engagements), and only 5 files in 1 engagement use OFFSET ... FETCH. Most grids paged in memory. The two queries above return 25 rows and one count, and an index on (CustomerId, InvoiceDate DESC, InvoiceId DESC) makes both cheap.

ToPagedResult covers IQueryable sources, including LINQ to Objects and Entity Framework Core. The partial view works for any PagedResult<T> through the non-generic IPagedResult interface.

Variations and pitfalls

  • Always order by a unique key as the last column. Without a deterministic order, rows can appear on two pages or on none.
  • With EF Core, write an async twin of ToPagedResult using CountAsync and ToListAsync from Microsoft.EntityFrameworkCore.
  • OFFSET gets slower on deep pages because SQL Server still reads the skipped rows. For "infinite scroll" or exports, use keyset paging: WHERE (InvoiceDate, InvoiceId) < (@LastDate, @LastId), expressed as InvoiceDate < @LastDate OR (InvoiceDate = @LastDate AND InvoiceId < @LastId).
  • If the count is expensive on huge tables, cache it briefly or show "more than 10,000" instead of an exact number.
  • When the requested page is past the end (records were deleted), the result has no items. Show a link back to page 1, or redirect to the last page.