pagination.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364
  1. from __future__ import annotations
  2. import typing as t
  3. from math import ceil
  4. import sqlalchemy as sa
  5. import sqlalchemy.orm as sa_orm
  6. from flask import abort
  7. from flask import request
  8. class Pagination:
  9. """Apply an offset and limit to the query based on the current page and number of
  10. items per page.
  11. Don't create pagination objects manually. They are created by
  12. :meth:`.SQLAlchemy.paginate` and :meth:`.Query.paginate`.
  13. This is a base class, a subclass must implement :meth:`_query_items` and
  14. :meth:`_query_count`. Those methods will use arguments passed as ``kwargs`` to
  15. perform the queries.
  16. :param page: The current page, used to calculate the offset. Defaults to the
  17. ``page`` query arg during a request, or 1 otherwise.
  18. :param per_page: The maximum number of items on a page, used to calculate the
  19. offset and limit. Defaults to the ``per_page`` query arg during a request,
  20. or 20 otherwise.
  21. :param max_per_page: The maximum allowed value for ``per_page``, to limit a
  22. user-provided value. Use ``None`` for no limit. Defaults to 100.
  23. :param error_out: Abort with a ``404 Not Found`` error if no items are returned
  24. and ``page`` is not 1, or if ``page`` or ``per_page`` is less than 1, or if
  25. either are not ints.
  26. :param count: Calculate the total number of values by issuing an extra count
  27. query. For very complex queries this may be inaccurate or slow, so it can be
  28. disabled and set manually if necessary.
  29. :param kwargs: Information about the query to paginate. Different subclasses will
  30. require different arguments.
  31. .. versionchanged:: 3.0
  32. Iterating over a pagination object iterates over its items.
  33. .. versionchanged:: 3.0
  34. Creating instances manually is not a public API.
  35. """
  36. def __init__(
  37. self,
  38. page: int | None = None,
  39. per_page: int | None = None,
  40. max_per_page: int | None = 100,
  41. error_out: bool = True,
  42. count: bool = True,
  43. **kwargs: t.Any,
  44. ) -> None:
  45. self._query_args = kwargs
  46. page, per_page = self._prepare_page_args(
  47. page=page,
  48. per_page=per_page,
  49. max_per_page=max_per_page,
  50. error_out=error_out,
  51. )
  52. self.page: int = page
  53. """The current page."""
  54. self.per_page: int = per_page
  55. """The maximum number of items on a page."""
  56. self.max_per_page: int | None = max_per_page
  57. """The maximum allowed value for ``per_page``."""
  58. items = self._query_items()
  59. if not items and page != 1 and error_out:
  60. abort(404)
  61. self.items: list[t.Any] = items
  62. """The items on the current page. Iterating over the pagination object is
  63. equivalent to iterating over the items.
  64. """
  65. if count:
  66. total = self._query_count()
  67. else:
  68. total = None
  69. self.total: int | None = total
  70. """The total number of items across all pages."""
  71. @staticmethod
  72. def _prepare_page_args(
  73. *,
  74. page: int | None = None,
  75. per_page: int | None = None,
  76. max_per_page: int | None = None,
  77. error_out: bool = True,
  78. ) -> tuple[int, int]:
  79. if request:
  80. if page is None:
  81. try:
  82. page = int(request.args.get("page", 1))
  83. except (TypeError, ValueError):
  84. if error_out:
  85. abort(404)
  86. page = 1
  87. if per_page is None:
  88. try:
  89. per_page = int(request.args.get("per_page", 20))
  90. except (TypeError, ValueError):
  91. if error_out:
  92. abort(404)
  93. per_page = 20
  94. else:
  95. if page is None:
  96. page = 1
  97. if per_page is None:
  98. per_page = 20
  99. if max_per_page is not None:
  100. per_page = min(per_page, max_per_page)
  101. if page < 1:
  102. if error_out:
  103. abort(404)
  104. else:
  105. page = 1
  106. if per_page < 1:
  107. if error_out:
  108. abort(404)
  109. else:
  110. per_page = 20
  111. return page, per_page
  112. @property
  113. def _query_offset(self) -> int:
  114. """The index of the first item to query, passed to ``offset()``.
  115. :meta private:
  116. .. versionadded:: 3.0
  117. """
  118. return (self.page - 1) * self.per_page
  119. def _query_items(self) -> list[t.Any]:
  120. """Execute the query to get the items on the current page.
  121. Uses init arguments stored in :attr:`_query_args`.
  122. :meta private:
  123. .. versionadded:: 3.0
  124. """
  125. raise NotImplementedError
  126. def _query_count(self) -> int:
  127. """Execute the query to get the total number of items.
  128. Uses init arguments stored in :attr:`_query_args`.
  129. :meta private:
  130. .. versionadded:: 3.0
  131. """
  132. raise NotImplementedError
  133. @property
  134. def first(self) -> int:
  135. """The number of the first item on the page, starting from 1, or 0 if there are
  136. no items.
  137. .. versionadded:: 3.0
  138. """
  139. if len(self.items) == 0:
  140. return 0
  141. return (self.page - 1) * self.per_page + 1
  142. @property
  143. def last(self) -> int:
  144. """The number of the last item on the page, starting from 1, inclusive, or 0 if
  145. there are no items.
  146. .. versionadded:: 3.0
  147. """
  148. first = self.first
  149. return max(first, first + len(self.items) - 1)
  150. @property
  151. def pages(self) -> int:
  152. """The total number of pages."""
  153. if self.total == 0 or self.total is None:
  154. return 0
  155. return ceil(self.total / self.per_page)
  156. @property
  157. def has_prev(self) -> bool:
  158. """``True`` if this is not the first page."""
  159. return self.page > 1
  160. @property
  161. def prev_num(self) -> int | None:
  162. """The previous page number, or ``None`` if this is the first page."""
  163. if not self.has_prev:
  164. return None
  165. return self.page - 1
  166. def prev(self, *, error_out: bool = False) -> Pagination:
  167. """Query the :class:`Pagination` object for the previous page.
  168. :param error_out: Abort with a ``404 Not Found`` error if no items are returned
  169. and ``page`` is not 1, or if ``page`` or ``per_page`` is less than 1, or if
  170. either are not ints.
  171. """
  172. p = type(self)(
  173. page=self.page - 1,
  174. per_page=self.per_page,
  175. error_out=error_out,
  176. count=False,
  177. **self._query_args,
  178. )
  179. p.total = self.total
  180. return p
  181. @property
  182. def has_next(self) -> bool:
  183. """``True`` if this is not the last page."""
  184. return self.page < self.pages
  185. @property
  186. def next_num(self) -> int | None:
  187. """The next page number, or ``None`` if this is the last page."""
  188. if not self.has_next:
  189. return None
  190. return self.page + 1
  191. def next(self, *, error_out: bool = False) -> Pagination:
  192. """Query the :class:`Pagination` object for the next page.
  193. :param error_out: Abort with a ``404 Not Found`` error if no items are returned
  194. and ``page`` is not 1, or if ``page`` or ``per_page`` is less than 1, or if
  195. either are not ints.
  196. """
  197. p = type(self)(
  198. page=self.page + 1,
  199. per_page=self.per_page,
  200. max_per_page=self.max_per_page,
  201. error_out=error_out,
  202. count=False,
  203. **self._query_args,
  204. )
  205. p.total = self.total
  206. return p
  207. def iter_pages(
  208. self,
  209. *,
  210. left_edge: int = 2,
  211. left_current: int = 2,
  212. right_current: int = 4,
  213. right_edge: int = 2,
  214. ) -> t.Iterator[int | None]:
  215. """Yield page numbers for a pagination widget. Skipped pages between the edges
  216. and middle are represented by a ``None``.
  217. For example, if there are 20 pages and the current page is 7, the following
  218. values are yielded.
  219. .. code-block:: python
  220. 1, 2, None, 5, 6, 7, 8, 9, 10, 11, None, 19, 20
  221. :param left_edge: How many pages to show from the first page.
  222. :param left_current: How many pages to show left of the current page.
  223. :param right_current: How many pages to show right of the current page.
  224. :param right_edge: How many pages to show from the last page.
  225. .. versionchanged:: 3.0
  226. Improved efficiency of calculating what to yield.
  227. .. versionchanged:: 3.0
  228. ``right_current`` boundary is inclusive.
  229. .. versionchanged:: 3.0
  230. All parameters are keyword-only.
  231. """
  232. pages_end = self.pages + 1
  233. if pages_end == 1:
  234. return
  235. left_end = min(1 + left_edge, pages_end)
  236. yield from range(1, left_end)
  237. if left_end == pages_end:
  238. return
  239. mid_start = max(left_end, self.page - left_current)
  240. mid_end = min(self.page + right_current + 1, pages_end)
  241. if mid_start - left_end > 0:
  242. yield None
  243. yield from range(mid_start, mid_end)
  244. if mid_end == pages_end:
  245. return
  246. right_start = max(mid_end, pages_end - right_edge)
  247. if right_start - mid_end > 0:
  248. yield None
  249. yield from range(right_start, pages_end)
  250. def __iter__(self) -> t.Iterator[t.Any]:
  251. yield from self.items
  252. class SelectPagination(Pagination):
  253. """Returned by :meth:`.SQLAlchemy.paginate`. Takes ``select`` and ``session``
  254. arguments in addition to the :class:`Pagination` arguments.
  255. .. versionadded:: 3.0
  256. """
  257. def _query_items(self) -> list[t.Any]:
  258. select = self._query_args["select"]
  259. select = select.limit(self.per_page).offset(self._query_offset)
  260. session = self._query_args["session"]
  261. return list(session.execute(select).unique().scalars())
  262. def _query_count(self) -> int:
  263. select = self._query_args["select"]
  264. sub = select.options(sa_orm.lazyload("*")).order_by(None).subquery()
  265. session = self._query_args["session"]
  266. out = session.execute(sa.select(sa.func.count()).select_from(sub)).scalar()
  267. return out # type: ignore[no-any-return]
  268. class QueryPagination(Pagination):
  269. """Returned by :meth:`.Query.paginate`. Takes a ``query`` argument in addition to
  270. the :class:`Pagination` arguments.
  271. .. versionadded:: 3.0
  272. """
  273. def _query_items(self) -> list[t.Any]:
  274. query = self._query_args["query"]
  275. out = query.limit(self.per_page).offset(self._query_offset).all()
  276. return out # type: ignore[no-any-return]
  277. def _query_count(self) -> int:
  278. # Query.count automatically disables eager loads
  279. out = self._query_args["query"].order_by(None).count()
  280. return out # type: ignore[no-any-return]