Files
DjangoAdmin_FastAPI_EleVue/shared/pagination.py
T
ClaudeandClaude bde742c7a8 feat(phase2): shared/ 共享层迁移
- shared/: enums/constants/pagination/base_model/base_db/base_repository/base_service
- apps/constants 与 apps/models/base_model、base_db 改为垫片
- 新增 pagination 单元测试

Co-Authored-By: Claude <noreply@anthropic.com>
2026-08-07 10:03:38 +08:00

55 lines
1.7 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# +======================================================================
# | DjangoAdmin 企业数字化开发平台 [ 赋能开发者,助力企业发展 ]
# +----------------------------------------------------------------------
# | Copyright (c) 2021-2026 一米阳光团队 版权所有
# | 开源协议: Apache-2.0
# +======================================================================
"""分页统一封装:解析 pageNo/pageSize 并对 SQLAlchemy query 应用分页。"""
from shared.constants import PAGE_SIZE
def get_page_params(query_params, default_size: int = PAGE_SIZE) -> tuple[int, int]:
"""
从 request.query_params 解析分页参数。
Args:
query_params: request.query_params(类 dict 对象)
default_size: 默认每页条数
Returns:
(page, size):page>=1,size>=1
"""
try:
page = int(query_params.get('pageNo', 1) or 1)
except (TypeError, ValueError):
page = 1
try:
size = int(query_params.get('pageSize', default_size) or default_size)
except (TypeError, ValueError):
size = default_size
if page < 1:
page = 1
if size < 1:
size = default_size
return page, size
def paginate_query(query, page: int, size: int) -> tuple[list, int]:
"""
对 SQLAlchemy query 应用分页并返回 (items, total)。
Args:
query: 已构建的 SQLAlchemy Query 对象(不含 count/limit/offset)
page: 页码(>=1)
size: 每页条数
Returns:
(items, total):当前页数据列表与总记录数
"""
total = query.count()
items = query.limit(size).offset((page - 1) * size).all()
return items, total