diff --git a/utils/pagination.py b/utils/pagination.py new file mode 100644 index 0000000..d9fba89 --- /dev/null +++ b/utils/pagination.py @@ -0,0 +1,39 @@ +"""分页通用工具:统一页码校验、偏移量和列表响应结构。""" +from __future__ import annotations + +from collections.abc import Sequence +from math import ceil +from typing import Any + + +def normalize_pagination( + page: int = 1, + page_size: int = 10, + *, + max_page_size: int = 10, +) -> tuple[int, int, int]: + """规范化分页参数,返回 ``(page, page_size, offset)``。""" + page = max(1, int(page)) + page_size = min(max_page_size, max(1, int(page_size))) + return page, page_size, (page - 1) * page_size + + +def pagination_result( + items: Sequence[Any], + total: int, + *, + page: int, + page_size: int, +) -> dict[str, Any]: + """构造统一分页响应,包含总页数供前端直接计算翻页状态。""" + total = max(0, int(total)) + return { + "items": list(items), + "total": total, + "page": page, + "page_size": page_size, + "total_pages": ceil(total / page_size) if total else 0, + } + + +__all__ = ["normalize_pagination", "pagination_result"]