Debian Codegraph @

ninja/pagination.py

raw symbols SCIP
1 import binascii
2 import inspect
3 from abc import ABC, abstractmethod
4 from base64 import b64decode, b64encode
5 from functools import partial, wraps
6 from math import inf
7 from typing import (
8 Any,
9 AsyncGenerator,
10 Callable,
11 List,
12 Optional,
13 Tuple,
14 Type,
15 Union,
16 )
17 from urllib import parse
18
19 from django.db.models import QuerySet
20 from django.http import HttpRequest
21 from django.utils.module_loading import import_string
22 from pydantic import BaseModel, field_validator
23 from typing_extensions import get_args as get_collection_args
24
25 from ninja import Field, Query, Router, Schema
26 from ninja.conf import settings
27 from ninja.constants import NOT_SET
28 from ninja.errors import ConfigError, ValidationError
29 from ninja.operation import Operation
30 from ninja.responses import Status
31 from ninja.signature.details import is_collection_type
32 from ninja.utils import (
33 contribute_operation_args,
34 contribute_operation_callback,
35 is_async_callable,
36 )
37
38
39 class PaginationBase(ABC):
40 class Input(Schema):
41 pass
42
43 InputSource = Query(...)
44
45 class Output(Schema):
46 items: List[Any]
47 count: int
48
49 items_attribute: str = "items"
50
51 def __init__(self, *, pass_parameter: Optional[str] = None, **kwargs: Any) -> None:
52 self.pass_parameter = pass_parameter
53
54 @abstractmethod
55 def paginate_queryset(
56 self,
57 queryset: QuerySet,
58 pagination: Any,
59 request: HttpRequest,
60 **params: Any,
61 ) -> Any:
62 pass # pragma: no cover
63
64 def _items_count(self, queryset: QuerySet) -> int:
65 """
66 Since lists are mainly compatible with QuerySets and can be passed to paginator.
67 We will first to try to use .count - and if not there will use a len
68 """
69 try:
70 # forcing to find queryset.count instead of list.count:
71 return queryset.all().count()
72 except AttributeError:
73 return len(queryset)
74
75
76 class AsyncPaginationBase(PaginationBase):
77 @abstractmethod
78 async def apaginate_queryset(
79 self,
80 queryset: QuerySet,
81 pagination: Any,
82 request: HttpRequest,
83 **params: Any,
84 ) -> Any:
85 pass # pragma: no cover
86
87 async def _aitems_count(self, queryset: QuerySet) -> int:
88 try:
89 return await queryset.all().acount()
90 except AttributeError:
91 return len(queryset)
92
93
94 class LimitOffsetPagination(AsyncPaginationBase):
95 class Input(Schema):
96 limit: int = Field(
97 settings.PAGINATION_PER_PAGE,
98 ge=1,
99 le=(
100 settings.PAGINATION_MAX_LIMIT
101 if settings.PAGINATION_MAX_LIMIT != inf
102 else None
103 ),
104 )
105 offset: int = Field(0, ge=0)
106
107 def paginate_queryset(
108 self,
109 queryset: QuerySet,
110 pagination: Input,
111 request: HttpRequest,
112 **params: Any,
113 ) -> Any:
114 offset = pagination.offset
115 limit: int = min(pagination.limit, settings.PAGINATION_MAX_LIMIT)
116 return {
117 self.items_attribute: queryset[offset : offset + limit],
118 "count": self._items_count(queryset),
119 } # noqa: E203
120
121 async def apaginate_queryset(
122 self,
123 queryset: QuerySet,
124 pagination: Input,
125 request: HttpRequest,
126 **params: Any,
127 ) -> Any:
128 offset = pagination.offset
129 limit: int = min(pagination.limit, settings.PAGINATION_MAX_LIMIT)
130 if isinstance(queryset, QuerySet):
131 items = [obj async for obj in queryset[offset : offset + limit]]
132 else:
133 items = queryset[offset : offset + limit]
134 return {
135 self.items_attribute: items,
136 "count": await self._aitems_count(queryset),
137 } # noqa: E203
138
139
140 class PageNumberPagination(AsyncPaginationBase):
141 class Input(Schema):
142 page: int = Field(1, ge=1)
143 page_size: Optional[int] = Field(None, ge=1)
144
145 def __init__(
146 self,
147 page_size: int = settings.PAGINATION_PER_PAGE,
148 max_page_size: int = settings.PAGINATION_MAX_PER_PAGE_SIZE,
149 **kwargs: Any,
150 ) -> None:
151 self.page_size = page_size
152 self.max_page_size = max_page_size
153 super().__init__(**kwargs)
154
155 def _get_page_size(self, requested_page_size: Optional[int]) -> int:
156 if requested_page_size is None:
157 return self.page_size
158
159 return min(requested_page_size, self.max_page_size)
160
161 def paginate_queryset(
162 self,
163 queryset: QuerySet,
164 pagination: Input,
165 request: HttpRequest,
166 **params: Any,
167 ) -> Any:
168 page_size = self._get_page_size(pagination.page_size)
169 offset = (pagination.page - 1) * page_size
170 return {
171 self.items_attribute: queryset[offset : offset + page_size],
172 "count": self._items_count(queryset),
173 } # noqa: E203
174
175 async def apaginate_queryset(
176 self,
177 queryset: QuerySet,
178 pagination: Input,
179 request: HttpRequest,
180 **params: Any,
181 ) -> Any:
182 page_size = self._get_page_size(pagination.page_size)
183 offset = (pagination.page - 1) * page_size
184
185 if isinstance(queryset, QuerySet):
186 items = [obj async for obj in queryset[offset : offset + page_size]]
187 else:
188 items = queryset[offset : offset + page_size]
189
190 return {
191 self.items_attribute: items,
192 "count": await self._aitems_count(queryset),
193 } # noqa: E203
194
195
196 class CursorPagination(AsyncPaginationBase):
197 max_page_size: int
198 page_size: int
199
200 items_attribute: str = "results"
201
202 def __init__(
203 self,
204 *,
205 ordering: Tuple[str, ...] = settings.PAGINATION_DEFAULT_ORDERING,
206 page_size: int = settings.PAGINATION_PER_PAGE,
207 max_page_size: int = settings.PAGINATION_MAX_PER_PAGE_SIZE,
208 **kwargs: Any,
209 ) -> None:
210 self.ordering = ordering
211 # take the first ordering parameter as the attribute for establishing
212 # position
213 self._order_attribute = (
214 ordering[0][1:] if ordering[0].startswith("-") else ordering[0]
215 )
216 self._order_attribute_reversed = ordering[0].startswith("-")
217
218 self.page_size = page_size
219 self.max_page_size = max_page_size
220
221 super().__init__(**kwargs)
222
223 class Input(Schema):
224 page_size: Optional[int] = None
225 cursor: Optional[str] = None
226
227 class Output(Schema):
228 previous: Optional[str]
229 next: Optional[str]
230 results: List[Any]
231
232 class Cursor(BaseModel):
233 """
234 Represents pagination state.
235
236 This is encoded in a base64 query parameter.
237
238 """
239
240 p: Optional[str] = Field(
241 default=None,
242 title="position",
243 description="String identifier for the current position in the dataset",
244 )
245
246 r: bool = Field(
247 default=False,
248 title="reverse",
249 description="Whether to reverse the ordering direction",
250 )
251
252 # offset enables the use of a non-unique ordering field
253 # e.g. if created time of two items is exactly the same, we can use the offset
254 # to figure out the position exactly
255 o: int = Field(
256 default=0,
257 ge=0,
258 lt=settings.PAGINATION_MAX_OFFSET,
259 title="offset",
260 description="Number of items to skip from the current position",
261 )
262
263 @field_validator("*", mode="before")
264 @classmethod
265 def validate_individual_queryparam(cls, value: Any) -> Any:
266 """
267 Handle query string parsing quirks where single values become lists.
268
269 URL parsing libraries wrap single query parameters in lists, we only
270 care about a single value
271 """
272 if isinstance(value, list):
273 return value[0]
274 return value
275
276 @classmethod
277 def from_encoded_param(
278 cls, encoded_param: Optional[str], context: Any = None
279 ) -> "CursorPagination.Cursor":
280 """
281 Deserialize cursor from URL-safe base64 token.
282 """
283 if not encoded_param:
284 return cls()
285 try:
286 decoded = b64decode(
287 encoded_param.encode("ascii"), validate=True
288 ).decode("ascii")
289 except (ValueError, binascii.Error) as e:
290 raise ValidationError([{"cursor": "Invalid Cursor"}]) from e
291
292 parsed_querystring = parse.parse_qs(decoded, keep_blank_values=True)
293 return cls.model_validate(parsed_querystring, context=context)
294
295 def encode_as_param(self) -> str:
296 """
297 Serialize cursor to URL-safe base64 token.
298 """
299 data = self.model_dump(
300 exclude_defaults=True, exclude_none=True, exclude_unset=True
301 )
302 query_string = parse.urlencode(data, doseq=True)
303 return b64encode(query_string.encode("ascii")).decode("ascii")
304
305 @staticmethod
306 def _reverse_order(order: Tuple[str, ...]) -> Tuple[str, ...]:
307 """
308 Flip ordering direction for backward pagination.
309
310 Example:
311 ("-created", "pk") becomes ("created", "-pk")
312 ("name", "-updated") becomes ("-name", "updated")
313 """
314 return tuple(
315 marker[1:] if marker.startswith("-") else f"-{marker}" for marker in order
316 )
317
318 def _get_position(self, item: Any) -> str:
319 """
320 Extract the string representation of the attribute value used for ordering,
321 which serves as the position identifier.
322
323 """
324 return str(getattr(item, self._order_attribute))
325
326 def _get_page_size(self, requested_page_size: Optional[int]) -> int:
327 """
328 Determine the actual page size to use, respecting configured limits.
329
330 Uses the default page size when no specific size is requested, otherwise
331 clamps the requested size within the allowed range to prevent resource
332 exhaustion attacks.
333 """
334 if requested_page_size is None:
335 return self.page_size
336 return min(self.max_page_size, max(1, requested_page_size))
337
338 def _build_next_cursor(
339 self,
340 current_cursor: Cursor,
341 results: List[Any],
342 additional_position: Optional[str] = None,
343 ) -> Optional[Cursor]:
344 """
345 Build cursor for next page
346 """
347 if (additional_position is None and not current_cursor.r) or not results:
348 return None
349
350 if not current_cursor.r:
351 # next position is provided by the additional position in a forward cursor
352 next_position = additional_position
353 else:
354 # default to the last item
355 # this will result in this item being included in the next set of results
356 # when flipping from a reversed cursor query to a forward cursor query
357 next_position = self._get_position(results[-1])
358
359 offset = 0
360
361 if current_cursor.p == next_position and not current_cursor.r:
362 offset += current_cursor.o + len(results)
363 else:
364 # Count duplicates at page end to find the offset
365 for item in reversed(results):
366 item_position_value = self._get_position(item)
367 if item_position_value != next_position:
368 break
369 offset += 1
370
371 return self.Cursor(o=offset, r=False, p=next_position)
372
373 def _build_previous_cursor(
374 self,
375 current_cursor: Cursor,
376 results: List[Any],
377 additional_position: Optional[str] = None,
378 ) -> Optional[Cursor]:
379 """
380 Build cursor for previous page
381 """
382 if (
383 current_cursor.r and additional_position is None
384 ) or current_cursor.p is None:
385 return None
386
387 if not results:
388 # End of dataset - create reverse cursor to go backward
389 return self.Cursor(o=0, r=True, p=current_cursor.p)
390
391 if current_cursor.r:
392 # previous position is provided by the additional position in a
393 # reversed cursor
394 previous_position = additional_position
395
396 else:
397 # default to the first item
398 # this will result in this item being included in the previous set of
399 # results when flipping from a forward cursor query to a reversed
400 # cursor query
401 previous_position = self._get_position(results[0])
402
403 offset = 0
404
405 if current_cursor.p == previous_position and current_cursor.r:
406 offset += current_cursor.o + len(results)
407 else:
408 # Count duplicates at page end to find the offset
409 for item in results:
410 item_position_value = self._get_position(item)
411 if item_position_value != previous_position:
412 break
413 offset += 1
414
415 return self.Cursor(o=offset, r=True, p=previous_position)
416
417 @staticmethod
418 def _add_cursor_to_URL(url: str, cursor: Optional[Cursor]) -> Optional[str]:
419 """
420 Build pagination URLs with an encoded cursor.
421
422 Ignore any previous cursors but preserve any other query parameters
423
424 Example:
425 Given URL "https://api.example.com/pages?tag=hiring" and a cursor
426 with position "2024-01-01T10:00:00Z", returns:
427 "https://api.example.com/pages?cursor=cD0yMDI0LTAxLTAxVDEwJTNBMDA%3D&tag=hiring"
428 """
429
430 if cursor is None:
431 return None
432 (scheme, netloc, path, query, fragment) = parse.urlsplit(url)
433 query_dict = parse.parse_qs(query, keep_blank_values=True)
434 query_dict["cursor"] = [cursor.encode_as_param()]
435 query = parse.urlencode(sorted(query_dict.items()), doseq=True)
436 return parse.urlunsplit((scheme, netloc, path, query, fragment))
437
438 def _order_queryset(self, queryset: QuerySet, cursor: Cursor) -> QuerySet:
439 """
440 Apply ordering to queryset based on cursor direction.
441
442 For backward pagination (cursor.r=True), flips the ordering direction
443 to traverse the dataset in reverse.
444 """
445 if cursor.r:
446 return queryset.order_by(*self._reverse_order(self.ordering))
447
448 return queryset.order_by(*self.ordering)
449
450 def _find_position(self, queryset: QuerySet, cursor: Cursor) -> QuerySet:
451 """
452 Filter queryset to start from the cursor position.
453 """
454 if cursor.p is None:
455 return queryset
456
457 cmp = "gte" if cursor.r == self._order_attribute_reversed else "lte"
458 filters = {f"{self._order_attribute}__{cmp}": cursor.p}
459 return queryset.filter(**filters)
460
461 def paginate_queryset(
462 self, queryset: QuerySet, pagination: Input, request: HttpRequest, **params: Any
463 ) -> Any:
464 """
465 Execute cursor-based pagination with stable positioning.
466
467 We fetch page_size + 1 items to detect whether more pages exist without
468 requiring a separate count query. The extra item is discarded from results
469 but used for next/previous cursor generation.
470 """
471 page_size = self._get_page_size(pagination.page_size)
472 cursor = self.Cursor.from_encoded_param(pagination.cursor)
473
474 queryset = self._order_queryset(queryset, cursor)
475 queryset = self._find_position(queryset, cursor)
476
477 # fetch results here and turn into a list
478 results_plus_one = list(queryset[cursor.o : cursor.o + page_size + 1])
479 additional_position = (
480 self._get_position(results_plus_one[-1])
481 if len(results_plus_one) > page_size
482 else None
483 )
484
485 if cursor.r:
486 results = list(reversed(results_plus_one[:page_size]))
487 else:
488 results = results_plus_one[:page_size]
489
490 next_cursor = self._build_next_cursor(
491 current_cursor=cursor,
492 results=results,
493 additional_position=additional_position,
494 )
495
496 previous_cursor = self._build_previous_cursor(
497 current_cursor=cursor,
498 results=results,
499 additional_position=additional_position,
500 )
501
502 base_url = request.build_absolute_uri()
503
504 return {
505 "next": self._add_cursor_to_URL(base_url, next_cursor),
506 "previous": self._add_cursor_to_URL(base_url, previous_cursor),
507 self.items_attribute: results,
508 }
509
510 async def apaginate_queryset(
511 self,
512 queryset: QuerySet,
513 pagination: Input,
514 request: HttpRequest,
515 **params: Any,
516 ) -> Any:
517 """
518 Execute async cursor-based pagination with stable positioning.
519
520 We fetch page_size + 1 items to detect whether more pages exist without
521 requiring a separate count query. The extra item is discarded from results
522 but used for next/previous cursor generation.
523 """
524 page_size = self._get_page_size(pagination.page_size)
525 cursor = self.Cursor.from_encoded_param(pagination.cursor)
526
527 queryset = self._order_queryset(queryset, cursor)
528 queryset = self._find_position(queryset, cursor)
529
530 # fetch results here and turn into a list
531 results_plus_one = [
532 obj async for obj in queryset[cursor.o : cursor.o + page_size + 1]
533 ]
534 additional_position = (
535 self._get_position(results_plus_one[-1])
536 if len(results_plus_one) > page_size
537 else None
538 )
539
540 if cursor.r:
541 results = list(reversed(results_plus_one[:page_size]))
542 else:
543 results = results_plus_one[:page_size]
544
545 next_cursor = self._build_next_cursor(
546 current_cursor=cursor,
547 results=results,
548 additional_position=additional_position,
549 )
550
551 previous_cursor = self._build_previous_cursor(
552 current_cursor=cursor,
553 results=results,
554 additional_position=additional_position,
555 )
556
557 base_url = request.build_absolute_uri()
558
559 return {
560 "next": self._add_cursor_to_URL(base_url, next_cursor),
561 "previous": self._add_cursor_to_URL(base_url, previous_cursor),
562 self.items_attribute: results,
563 }
564
565
566 def paginate(
567 func_or_pgn_class: Any = NOT_SET, **paginator_params: Any
568 ) -> Callable[..., Any]:
569 """
570 @api.get(...
571 @paginate
572 def my_view(request):
573
574 or
575
576 @api.get(...
577 @paginate(PageNumberPagination)
578 def my_view(request):
579
580 """
581
582 isfunction = inspect.isfunction(func_or_pgn_class)
583 isnotset = func_or_pgn_class == NOT_SET
584
585 pagination_class: Type[Union[PaginationBase, AsyncPaginationBase]] = import_string(
586 settings.PAGINATION_CLASS
587 )
588
589 if isfunction:
590 return _inject_pagination(func_or_pgn_class, pagination_class)
591
592 if not isnotset:
593 pagination_class = func_or_pgn_class
594
595 def wrapper(func: Callable[..., Any]) -> Any:
596 return _inject_pagination(func, pagination_class, **paginator_params)
597
598 return wrapper
599
600
601 def _inject_pagination(
602 func: Callable[..., Any],
603 paginator_class: Type[Union[PaginationBase, AsyncPaginationBase]],
604 **paginator_params: Any,
605 ) -> Callable[..., Any]:
606 if getattr(func, "_ninja_is_paginated", False):
607 return func # ^ user changed pagination manually on function already
608
609 paginator = paginator_class(**paginator_params)
610
611 # Check if Input schema has any fields
612 # If it has no fields, we should make it optional to support Pydantic 2.12+
613 has_input_fields = bool(paginator.Input.model_fields)
614
615 if is_async_callable(func):
616 if not hasattr(paginator, "apaginate_queryset"):
617 raise ConfigError("Pagination class not configured for async requests")
618
619 @wraps(func)
620 async def view_with_pagination(request: HttpRequest, **kwargs: Any) -> Any:
621 pagination_params = kwargs.pop("ninja_pagination", None)
622 if pagination_params is None:
623 pagination_params = paginator.Input()
624 if paginator.pass_parameter:
625 kwargs[paginator.pass_parameter] = pagination_params
626
627 items = await func(request, **kwargs)
628
629 status_code = None
630 if isinstance(items, Status):
631 status_code = items.status_code
632 items = items.value
633
634 result = await paginator.apaginate_queryset(
635 items, pagination=pagination_params, request=request, **kwargs
636 )
637
638 async def evaluate(results: Union[List, QuerySet]) -> AsyncGenerator:
639 for result in results:
640 yield result
641
642 if paginator.Output: # type: ignore
643 result[paginator.items_attribute] = [
644 result
645 async for result in evaluate(result[paginator.items_attribute])
646 ]
647
648 if status_code is not None:
649 return Status(status_code, result)
650 return result
651
652 else:
653
654 @wraps(func)
655 def view_with_pagination(request: HttpRequest, **kwargs: Any) -> Any:
656 pagination_params = kwargs.pop("ninja_pagination", None)
657 if pagination_params is None:
658 pagination_params = paginator.Input()
659 if paginator.pass_parameter:
660 kwargs[paginator.pass_parameter] = pagination_params
661
662 items = func(request, **kwargs)
663
664 status_code = None
665 if isinstance(items, Status):
666 status_code = items.status_code
667 items = items.value
668
669 result = paginator.paginate_queryset(
670 items, pagination=pagination_params, request=request, **kwargs
671 )
672 if paginator.Output: # type: ignore
673 result[paginator.items_attribute] = list(
674 result[paginator.items_attribute]
675 )
676 # ^ forcing queryset evaluation #TODO: check why pydantic did not do it here
677
678 if status_code is not None:
679 return Status(status_code, result)
680 return result
681
682 # Only contribute args if Input has fields
683 # For empty Input schemas, don't add the parameter at all to support Pydantic 2.12+
684 if has_input_fields:
685 contribute_operation_args(
686 view_with_pagination,
687 "ninja_pagination",
688 paginator.Input,
689 paginator.InputSource,
690 )
691
692 if paginator.Output: # type: ignore
693 contribute_operation_callback(
694 view_with_pagination,
695 partial(make_response_paginated, paginator),
696 )
697
698 view_with_pagination._ninja_is_paginated = True # type: ignore
699 return view_with_pagination
700
701
702 class RouterPaginated(Router):
703 def __init__(self, *args: Any, **kwargs: Any) -> None:
704 super().__init__(*args, **kwargs)
705 self.pagination_class = import_string(settings.PAGINATION_CLASS)
706
707 def add_api_operation(
708 self,
709 path: str,
710 methods: List[str],
711 view_func: Callable[..., Any],
712 **kwargs: Any,
713 ) -> None:
714 response = kwargs["response"]
715 if is_collection_type(response):
716 view_func = _inject_pagination(view_func, self.pagination_class)
717 return super().add_api_operation(path, methods, view_func, **kwargs)
718
719
720 def make_response_paginated(paginator: PaginationBase, op: Operation) -> None:
721 """
722 Takes operation response and changes it to the paginated response
723 for example:
724 response=List[Some]
725 will be changed to:
726 response=PagedSome
727 where Paged some will be a subclass of paginator.Output:
728 class PagedSome:
729 items: List[Some]
730 count: int
731 """
732 status_code, item_schema = _find_collection_response(op)
733
734 # Switching schema to Output schema
735 try:
736 new_name = f"Paged{item_schema.__name__}"
737 except AttributeError: # pragma: no cover
738 # special case for `typing.Any`, only raised for Python < 3.10
739 new_name = f"Paged{str(item_schema).replace('.', '_')}" # pragma: no cover
740 new_schema = type(
741 new_name,
742 (paginator.Output,),
743 {
744 "__annotations__": {paginator.items_attribute: List[item_schema]}, # type: ignore
745 },
746 ) # typing: ignore
747
748 response = op._create_response_model(new_schema)
749
750 # Changing response model to newly created one
751 op.response_models[status_code] = response
752
753
754 def _find_collection_response(op: Operation) -> Tuple[int, Any]:
755 """
756 Walks through defined operation responses and finds the first
757 that is of a collection type (e.g. List[SomeSchema])
758 """
759 for code, resp_model in op.response_models.items():
760 if resp_model is None or resp_model is NOT_SET:
761 continue
762
763 model = resp_model.__annotations__["response"]
764 if is_collection_type(model):
765 item_schema = get_collection_args(model)[0]
766 return code, item_schema
767
768 raise ConfigError(
769 f'"{op.view_func}" has no collection response (e.g. response=List[SomeSchema])'
770 )