From b67054c9e1b523f25bb4852315f569bed9fa1259 Mon Sep 17 00:00:00 2001 From: "alex.lambdaloopers" Date: Mon, 9 Sep 2024 11:01:08 +0200 Subject: [PATCH] fix: clamp page if it exceeds the maximum page --- sqladmin/models.py | 3 +++ sqladmin/pagination.py | 3 +++ tests/test_application.py | 2 +- 3 files changed, 7 insertions(+), 1 deletion(-) diff --git a/sqladmin/models.py b/sqladmin/models.py index d201be3f..6b030337 100644 --- a/sqladmin/models.py +++ b/sqladmin/models.py @@ -810,6 +810,9 @@ async def list(self, request: Request) -> Pagination: else: count = await self.count(request) + # Clamp page + page = min(page, max(1, count // page_size + 1)) + stmt = stmt.limit(page_size).offset((page - 1) * page_size) rows = await self._run_query(stmt) diff --git a/sqladmin/pagination.py b/sqladmin/pagination.py index 3e8d122e..8a38b86d 100644 --- a/sqladmin/pagination.py +++ b/sqladmin/pagination.py @@ -52,6 +52,9 @@ def resize(self, page_size: int) -> Pagination: return self def add_pagination_urls(self, base_url: URL) -> None: + # Clamp page + self.page = min(self.page, max(1, self.count // self.page_size + 1)) + # Previous pages for p in range(self.page - min(self.max_page_controls, 3), self.page): if p > 0: diff --git a/tests/test_application.py b/tests/test_application.py index a7bf9710..7c3ee409 100644 --- a/tests/test_application.py +++ b/tests/test_application.py @@ -177,7 +177,7 @@ class UserAdmin(ModelView, model=User): client = TestClient(app) response = client.get("/admin/user/list?page=10000") - assert response.status_code == 400 + assert response.status_code == 200 response = client.get("/admin/user/list?page=aaaa") assert response.status_code == 400