| 1 |
""" |
| 2 |
Pagination serializers determine the structure of the output that should |
| 3 |
be used for paginated responses. |
| 4 |
""" |
| 5 |
|
| 6 |
import contextlib |
| 7 |
from base64 import b64decode, b64encode |
| 8 |
from collections import namedtuple |
| 9 |
from urllib import parse |
| 10 |
|
| 11 |
from django.core.paginator import InvalidPage |
| 12 |
from django.core.paginator import Paginator as DjangoPaginator |
| 13 |
from django.template import loader |
| 14 |
from django.utils.encoding import force_str |
| 15 |
from django.utils.translation import gettext_lazy as _ |
| 16 |
|
| 17 |
from rest_framework.exceptions import NotFound |
| 18 |
from rest_framework.response import Response |
| 19 |
from rest_framework.settings import api_settings |
| 20 |
from rest_framework.utils.urls import remove_query_param, replace_query_param |
| 21 |
|
| 22 |
|
| 23 |
def _positive_int(integer_string, strict=False, cutoff=None): |
| 24 |
""" |
| 25 |
Cast a string to a strictly positive integer. |
| 26 |
""" |
| 27 |
ret = int(integer_string) |
| 28 |
if ret < 0 or (ret == 0 and strict): |
| 29 |
raise ValueError() |
| 30 |
if cutoff: |
| 31 |
return min(ret, cutoff) |
| 32 |
return ret |
| 33 |
|
| 34 |
|
| 35 |
def _divide_with_ceil(a, b): |
| 36 |
""" |
| 37 |
Returns 'a' divided by 'b', with any remainder rounded up. |
| 38 |
""" |
| 39 |
if a % b: |
| 40 |
return (a // b) + 1 |
| 41 |
|
| 42 |
return a // b |
| 43 |
|
| 44 |
|
| 45 |
def _get_displayed_page_numbers(current, final): |
| 46 |
""" |
| 47 |
This utility function determines a list of page numbers to display. |
| 48 |
This gives us a nice contextually relevant set of page numbers. |
| 49 |
|
| 50 |
For example: |
| 51 |
current=14, final=16 -> [1, None, 13, 14, 15, 16] |
| 52 |
|
| 53 |
This implementation gives one page to each side of the cursor, |
| 54 |
or two pages to the side when the cursor is at the edge, then |
| 55 |
ensures that any breaks between non-continuous page numbers never |
| 56 |
remove only a single page. |
| 57 |
|
| 58 |
For an alternative implementation which gives two pages to each side of |
| 59 |
the cursor, eg. as in GitHub issue list pagination, see: |
| 60 |
|
| 61 |
https://gist.github.com/tomchristie/321140cebb1c4a558b15 |
| 62 |
""" |
| 63 |
assert current >= 1 |
| 64 |
assert final >= current |
| 65 |
|
| 66 |
if final <= 5: |
| 67 |
return list(range(1, final + 1)) |
| 68 |
|
| 69 |
# We always include the first two pages, last two pages, and |
| 70 |
# two pages either side of the current page. |
| 71 |
included = {1, current - 1, current, current + 1, final} |
| 72 |
|
| 73 |
# If the break would only exclude a single page number then we |
| 74 |
# may as well include the page number instead of the break. |
| 75 |
if current <= 4: |
| 76 |
included.add(2) |
| 77 |
included.add(3) |
| 78 |
if current >= final - 3: |
| 79 |
included.add(final - 1) |
| 80 |
included.add(final - 2) |
| 81 |
|
| 82 |
# Now sort the page numbers and drop anything outside the limits. |
| 83 |
included = [ |
| 84 |
idx for idx in sorted(included) |
| 85 |
if 0 < idx <= final |
| 86 |
] |
| 87 |
|
| 88 |
# Finally insert any `...` breaks |
| 89 |
if current > 4: |
| 90 |
included.insert(1, None) |
| 91 |
if current < final - 3: |
| 92 |
included.insert(len(included) - 1, None) |
| 93 |
return included |
| 94 |
|
| 95 |
|
| 96 |
def _get_page_links(page_numbers, current, url_func): |
| 97 |
""" |
| 98 |
Given a list of page numbers and `None` page breaks, |
| 99 |
return a list of `PageLink` objects. |
| 100 |
""" |
| 101 |
page_links = [] |
| 102 |
for page_number in page_numbers: |
| 103 |
if page_number is None: |
| 104 |
page_link = PAGE_BREAK |
| 105 |
else: |
| 106 |
page_link = PageLink( |
| 107 |
url=url_func(page_number), |
| 108 |
number=page_number, |
| 109 |
is_active=(page_number == current), |
| 110 |
is_break=False |
| 111 |
) |
| 112 |
page_links.append(page_link) |
| 113 |
return page_links |
| 114 |
|
| 115 |
|
| 116 |
def _reverse_ordering(ordering_tuple): |
| 117 |
""" |
| 118 |
Given an order_by tuple such as `('-created', 'uuid')` reverse the |
| 119 |
ordering and return a new tuple, eg. `('created', '-uuid')`. |
| 120 |
""" |
| 121 |
def invert(x): |
| 122 |
return x[1:] if x.startswith('-') else '-' + x |
| 123 |
|
| 124 |
return tuple([invert(item) for item in ordering_tuple]) |
| 125 |
|
| 126 |
|
| 127 |
Cursor = namedtuple('Cursor', ['offset', 'reverse', 'position']) |
| 128 |
PageLink = namedtuple('PageLink', ['url', 'number', 'is_active', 'is_break']) |
| 129 |
|
| 130 |
PAGE_BREAK = PageLink(url=None, number=None, is_active=False, is_break=True) |
| 131 |
|
| 132 |
|
| 133 |
class BasePagination: |
| 134 |
display_page_controls = False |
| 135 |
|
| 136 |
def paginate_queryset(self, queryset, request, view=None): # pragma: no cover |
| 137 |
raise NotImplementedError('paginate_queryset() must be implemented.') |
| 138 |
|
| 139 |
def get_paginated_response(self, data): # pragma: no cover |
| 140 |
raise NotImplementedError('get_paginated_response() must be implemented.') |
| 141 |
|
| 142 |
def get_paginated_response_schema(self, schema): |
| 143 |
return schema |
| 144 |
|
| 145 |
def to_html(self): # pragma: no cover |
| 146 |
raise NotImplementedError('to_html() must be implemented to display page controls.') |
| 147 |
|
| 148 |
def get_results(self, data): |
| 149 |
return data['results'] |
| 150 |
|
| 151 |
def get_schema_operation_parameters(self, view): |
| 152 |
return [] |
| 153 |
|
| 154 |
|
| 155 |
class PageNumberPagination(BasePagination): |
| 156 |
""" |
| 157 |
A simple page number based style that supports page numbers as |
| 158 |
query parameters. For example: |
| 159 |
|
| 160 |
http://api.example.org/accounts/?page=4 |
| 161 |
http://api.example.org/accounts/?page=4&page_size=100 |
| 162 |
""" |
| 163 |
# The default page size. |
| 164 |
# Defaults to `None`, meaning pagination is disabled. |
| 165 |
page_size = api_settings.PAGE_SIZE |
| 166 |
|
| 167 |
django_paginator_class = DjangoPaginator |
| 168 |
|
| 169 |
# Client can control the page using this query parameter. |
| 170 |
page_query_param = 'page' |
| 171 |
page_query_description = _('A page number within the paginated result set.') |
| 172 |
|
| 173 |
# Client can control the page size using this query parameter. |
| 174 |
# Default is 'None'. Set to eg 'page_size' to enable usage. |
| 175 |
page_size_query_param = None |
| 176 |
page_size_query_description = _('Number of results to return per page.') |
| 177 |
|
| 178 |
# Set to an integer to limit the maximum page size the client may request. |
| 179 |
# Only relevant if 'page_size_query_param' has also been set. |
| 180 |
max_page_size = None |
| 181 |
|
| 182 |
last_page_strings = ('last',) |
| 183 |
|
| 184 |
template = 'rest_framework/pagination/numbers.html' |
| 185 |
|
| 186 |
invalid_page_message = _('Invalid page.') |
| 187 |
|
| 188 |
def paginate_queryset(self, queryset, request, view=None): |
| 189 |
""" |
| 190 |
Paginate a queryset if required, either returning a |
| 191 |
page object, or `None` if pagination is not configured for this view. |
| 192 |
""" |
| 193 |
self.request = request |
| 194 |
page_size = self.get_page_size(request) |
| 195 |
if not page_size: |
| 196 |
return None |
| 197 |
|
| 198 |
paginator = self.django_paginator_class(queryset, page_size) |
| 199 |
page_number = self.get_page_number(request, paginator) |
| 200 |
|
| 201 |
try: |
| 202 |
self.page = paginator.page(page_number) |
| 203 |
except InvalidPage as exc: |
| 204 |
msg = self.invalid_page_message.format( |
| 205 |
page_number=page_number, message=str(exc) |
| 206 |
) |
| 207 |
raise NotFound(msg) |
| 208 |
|
| 209 |
if paginator.num_pages > 1 and self.template is not None: |
| 210 |
# The browsable API should display pagination controls. |
| 211 |
self.display_page_controls = True |
| 212 |
|
| 213 |
return list(self.page) |
| 214 |
|
| 215 |
def get_page_number(self, request, paginator): |
| 216 |
page_number = request.query_params.get(self.page_query_param) or 1 |
| 217 |
if page_number in self.last_page_strings: |
| 218 |
page_number = paginator.num_pages |
| 219 |
return page_number |
| 220 |
|
| 221 |
def get_paginated_response(self, data): |
| 222 |
return Response({ |
| 223 |
'count': self.page.paginator.count, |
| 224 |
'next': self.get_next_link(), |
| 225 |
'previous': self.get_previous_link(), |
| 226 |
'results': data, |
| 227 |
}) |
| 228 |
|
| 229 |
def get_paginated_response_schema(self, schema): |
| 230 |
return { |
| 231 |
'type': 'object', |
| 232 |
'required': ['count', 'results'], |
| 233 |
'properties': { |
| 234 |
'count': { |
| 235 |
'type': 'integer', |
| 236 |
'example': 123, |
| 237 |
}, |
| 238 |
'next': { |
| 239 |
'type': 'string', |
| 240 |
'nullable': True, |
| 241 |
'format': 'uri', |
| 242 |
'example': 'http://api.example.org/accounts/?{page_query_param}=4'.format( |
| 243 |
page_query_param=self.page_query_param) |
| 244 |
}, |
| 245 |
'previous': { |
| 246 |
'type': 'string', |
| 247 |
'nullable': True, |
| 248 |
'format': 'uri', |
| 249 |
'example': 'http://api.example.org/accounts/?{page_query_param}=2'.format( |
| 250 |
page_query_param=self.page_query_param) |
| 251 |
}, |
| 252 |
'results': schema, |
| 253 |
}, |
| 254 |
} |
| 255 |
|
| 256 |
def get_page_size(self, request): |
| 257 |
if self.page_size_query_param: |
| 258 |
with contextlib.suppress(KeyError, ValueError): |
| 259 |
return _positive_int( |
| 260 |
request.query_params[self.page_size_query_param], |
| 261 |
strict=True, |
| 262 |
cutoff=self.max_page_size |
| 263 |
) |
| 264 |
return self.page_size |
| 265 |
|
| 266 |
def get_next_link(self): |
| 267 |
if not self.page.has_next(): |
| 268 |
return None |
| 269 |
url = self.request.build_absolute_uri() |
| 270 |
page_number = self.page.next_page_number() |
| 271 |
return replace_query_param(url, self.page_query_param, page_number) |
| 272 |
|
| 273 |
def get_previous_link(self): |
| 274 |
if not self.page.has_previous(): |
| 275 |
return None |
| 276 |
url = self.request.build_absolute_uri() |
| 277 |
page_number = self.page.previous_page_number() |
| 278 |
if page_number == 1: |
| 279 |
return remove_query_param(url, self.page_query_param) |
| 280 |
return replace_query_param(url, self.page_query_param, page_number) |
| 281 |
|
| 282 |
def get_html_context(self): |
| 283 |
base_url = self.request.build_absolute_uri() |
| 284 |
|
| 285 |
def page_number_to_url(page_number): |
| 286 |
if page_number == 1: |
| 287 |
return remove_query_param(base_url, self.page_query_param) |
| 288 |
else: |
| 289 |
return replace_query_param(base_url, self.page_query_param, page_number) |
| 290 |
|
| 291 |
current = self.page.number |
| 292 |
final = self.page.paginator.num_pages |
| 293 |
page_numbers = _get_displayed_page_numbers(current, final) |
| 294 |
page_links = _get_page_links(page_numbers, current, page_number_to_url) |
| 295 |
|
| 296 |
return { |
| 297 |
'previous_url': self.get_previous_link(), |
| 298 |
'next_url': self.get_next_link(), |
| 299 |
'page_links': page_links |
| 300 |
} |
| 301 |
|
| 302 |
def to_html(self): |
| 303 |
template = loader.get_template(self.template) |
| 304 |
context = self.get_html_context() |
| 305 |
return template.render(context) |
| 306 |
|
| 307 |
def get_schema_operation_parameters(self, view): |
| 308 |
parameters = [ |
| 309 |
{ |
| 310 |
'name': self.page_query_param, |
| 311 |
'required': False, |
| 312 |
'in': 'query', |
| 313 |
'description': force_str(self.page_query_description), |
| 314 |
'schema': { |
| 315 |
'type': 'integer', |
| 316 |
}, |
| 317 |
}, |
| 318 |
] |
| 319 |
if self.page_size_query_param is not None: |
| 320 |
parameters.append( |
| 321 |
{ |
| 322 |
'name': self.page_size_query_param, |
| 323 |
'required': False, |
| 324 |
'in': 'query', |
| 325 |
'description': force_str(self.page_size_query_description), |
| 326 |
'schema': { |
| 327 |
'type': 'integer', |
| 328 |
}, |
| 329 |
}, |
| 330 |
) |
| 331 |
return parameters |
| 332 |
|
| 333 |
|
| 334 |
class LimitOffsetPagination(BasePagination): |
| 335 |
""" |
| 336 |
A limit/offset based style. For example: |
| 337 |
|
| 338 |
http://api.example.org/accounts/?limit=100 |
| 339 |
http://api.example.org/accounts/?offset=400&limit=100 |
| 340 |
""" |
| 341 |
default_limit = api_settings.PAGE_SIZE |
| 342 |
limit_query_param = 'limit' |
| 343 |
limit_query_description = _('Number of results to return per page.') |
| 344 |
offset_query_param = 'offset' |
| 345 |
offset_query_description = _('The initial index from which to return the results.') |
| 346 |
max_limit = None |
| 347 |
template = 'rest_framework/pagination/numbers.html' |
| 348 |
|
| 349 |
def paginate_queryset(self, queryset, request, view=None): |
| 350 |
self.request = request |
| 351 |
self.limit = self.get_limit(request) |
| 352 |
if self.limit is None: |
| 353 |
return None |
| 354 |
|
| 355 |
self.count = self.get_count(queryset) |
| 356 |
self.offset = self.get_offset(request) |
| 357 |
if self.count > self.limit and self.template is not None: |
| 358 |
self.display_page_controls = True |
| 359 |
|
| 360 |
if self.count == 0 or self.offset > self.count: |
| 361 |
return [] |
| 362 |
return list(queryset[self.offset:self.offset + self.limit]) |
| 363 |
|
| 364 |
def get_paginated_response(self, data): |
| 365 |
return Response({ |
| 366 |
'count': self.count, |
| 367 |
'next': self.get_next_link(), |
| 368 |
'previous': self.get_previous_link(), |
| 369 |
'results': data |
| 370 |
}) |
| 371 |
|
| 372 |
def get_paginated_response_schema(self, schema): |
| 373 |
return { |
| 374 |
'type': 'object', |
| 375 |
'required': ['count', 'results'], |
| 376 |
'properties': { |
| 377 |
'count': { |
| 378 |
'type': 'integer', |
| 379 |
'example': 123, |
| 380 |
}, |
| 381 |
'next': { |
| 382 |
'type': 'string', |
| 383 |
'nullable': True, |
| 384 |
'format': 'uri', |
| 385 |
'example': 'http://api.example.org/accounts/?{offset_param}=400&{limit_param}=100'.format( |
| 386 |
offset_param=self.offset_query_param, limit_param=self.limit_query_param), |
| 387 |
}, |
| 388 |
'previous': { |
| 389 |
'type': 'string', |
| 390 |
'nullable': True, |
| 391 |
'format': 'uri', |
| 392 |
'example': 'http://api.example.org/accounts/?{offset_param}=200&{limit_param}=100'.format( |
| 393 |
offset_param=self.offset_query_param, limit_param=self.limit_query_param), |
| 394 |
}, |
| 395 |
'results': schema, |
| 396 |
}, |
| 397 |
} |
| 398 |
|
| 399 |
def get_limit(self, request): |
| 400 |
if self.limit_query_param: |
| 401 |
with contextlib.suppress(KeyError, ValueError): |
| 402 |
return _positive_int( |
| 403 |
request.query_params[self.limit_query_param], |
| 404 |
strict=True, |
| 405 |
cutoff=self.max_limit |
| 406 |
) |
| 407 |
return self.default_limit |
| 408 |
|
| 409 |
def get_offset(self, request): |
| 410 |
try: |
| 411 |
return _positive_int( |
| 412 |
request.query_params[self.offset_query_param], |
| 413 |
) |
| 414 |
except (KeyError, ValueError): |
| 415 |
return 0 |
| 416 |
|
| 417 |
def get_next_link(self): |
| 418 |
if self.offset + self.limit >= self.count: |
| 419 |
return None |
| 420 |
|
| 421 |
url = self.request.build_absolute_uri() |
| 422 |
url = replace_query_param(url, self.limit_query_param, self.limit) |
| 423 |
|
| 424 |
offset = self.offset + self.limit |
| 425 |
return replace_query_param(url, self.offset_query_param, offset) |
| 426 |
|
| 427 |
def get_previous_link(self): |
| 428 |
if self.offset <= 0: |
| 429 |
return None |
| 430 |
|
| 431 |
url = self.request.build_absolute_uri() |
| 432 |
url = replace_query_param(url, self.limit_query_param, self.limit) |
| 433 |
|
| 434 |
if self.offset - self.limit <= 0: |
| 435 |
return remove_query_param(url, self.offset_query_param) |
| 436 |
|
| 437 |
offset = self.offset - self.limit |
| 438 |
return replace_query_param(url, self.offset_query_param, offset) |
| 439 |
|
| 440 |
def get_html_context(self): |
| 441 |
base_url = self.request.build_absolute_uri() |
| 442 |
|
| 443 |
if self.limit: |
| 444 |
current = _divide_with_ceil(self.offset, self.limit) + 1 |
| 445 |
|
| 446 |
# The number of pages is a little bit fiddly. |
| 447 |
# We need to sum both the number of pages from current offset to end |
| 448 |
# plus the number of pages up to the current offset. |
| 449 |
# When offset is not strictly divisible by the limit then we may |
| 450 |
# end up introducing an extra page as an artifact. |
| 451 |
final = ( |
| 452 |
_divide_with_ceil(self.count - self.offset, self.limit) + |
| 453 |
_divide_with_ceil(self.offset, self.limit) |
| 454 |
) |
| 455 |
|
| 456 |
final = max(final, 1) |
| 457 |
else: |
| 458 |
current = 1 |
| 459 |
final = 1 |
| 460 |
|
| 461 |
if current > final: |
| 462 |
current = final |
| 463 |
|
| 464 |
def page_number_to_url(page_number): |
| 465 |
if page_number == 1: |
| 466 |
return remove_query_param(base_url, self.offset_query_param) |
| 467 |
else: |
| 468 |
offset = self.offset + ((page_number - current) * self.limit) |
| 469 |
return replace_query_param(base_url, self.offset_query_param, offset) |
| 470 |
|
| 471 |
page_numbers = _get_displayed_page_numbers(current, final) |
| 472 |
page_links = _get_page_links(page_numbers, current, page_number_to_url) |
| 473 |
|
| 474 |
return { |
| 475 |
'previous_url': self.get_previous_link(), |
| 476 |
'next_url': self.get_next_link(), |
| 477 |
'page_links': page_links |
| 478 |
} |
| 479 |
|
| 480 |
def to_html(self): |
| 481 |
template = loader.get_template(self.template) |
| 482 |
context = self.get_html_context() |
| 483 |
return template.render(context) |
| 484 |
|
| 485 |
def get_count(self, queryset): |
| 486 |
""" |
| 487 |
Determine an object count, supporting either querysets or regular lists. |
| 488 |
""" |
| 489 |
try: |
| 490 |
return queryset.count() |
| 491 |
except (AttributeError, TypeError): |
| 492 |
return len(queryset) |
| 493 |
|
| 494 |
def get_schema_operation_parameters(self, view): |
| 495 |
parameters = [ |
| 496 |
{ |
| 497 |
'name': self.limit_query_param, |
| 498 |
'required': False, |
| 499 |
'in': 'query', |
| 500 |
'description': force_str(self.limit_query_description), |
| 501 |
'schema': { |
| 502 |
'type': 'integer', |
| 503 |
}, |
| 504 |
}, |
| 505 |
{ |
| 506 |
'name': self.offset_query_param, |
| 507 |
'required': False, |
| 508 |
'in': 'query', |
| 509 |
'description': force_str(self.offset_query_description), |
| 510 |
'schema': { |
| 511 |
'type': 'integer', |
| 512 |
}, |
| 513 |
}, |
| 514 |
] |
| 515 |
return parameters |
| 516 |
|
| 517 |
|
| 518 |
class CursorPagination(BasePagination): |
| 519 |
""" |
| 520 |
The cursor pagination implementation is necessarily complex. |
| 521 |
For an overview of the position/offset style we use, see this post: |
| 522 |
https://cra.mr/2011/03/08/building-cursors-for-the-disqus-api |
| 523 |
""" |
| 524 |
cursor_query_param = 'cursor' |
| 525 |
cursor_query_description = _('The pagination cursor value.') |
| 526 |
page_size = api_settings.PAGE_SIZE |
| 527 |
invalid_cursor_message = _('Invalid cursor') |
| 528 |
ordering = '-created' |
| 529 |
template = 'rest_framework/pagination/previous_and_next.html' |
| 530 |
|
| 531 |
# Client can control the page size using this query parameter. |
| 532 |
# Default is 'None'. Set to eg 'page_size' to enable usage. |
| 533 |
page_size_query_param = None |
| 534 |
page_size_query_description = _('Number of results to return per page.') |
| 535 |
|
| 536 |
# Set to an integer to limit the maximum page size the client may request. |
| 537 |
# Only relevant if 'page_size_query_param' has also been set. |
| 538 |
max_page_size = None |
| 539 |
|
| 540 |
# The offset in the cursor is used in situations where we have a |
| 541 |
# nearly-unique index. (Eg millisecond precision creation timestamps) |
| 542 |
# We guard against malicious users attempting to cause expensive database |
| 543 |
# queries, by having a hard cap on the maximum possible size of the offset. |
| 544 |
offset_cutoff = 1000 |
| 545 |
|
| 546 |
def paginate_queryset(self, queryset, request, view=None): |
| 547 |
self.request = request |
| 548 |
self.page_size = self.get_page_size(request) |
| 549 |
if not self.page_size: |
| 550 |
return None |
| 551 |
|
| 552 |
self.base_url = request.build_absolute_uri() |
| 553 |
self.ordering = self.get_ordering(request, queryset, view) |
| 554 |
|
| 555 |
self.cursor = self.decode_cursor(request) |
| 556 |
if self.cursor is None: |
| 557 |
(offset, reverse, current_position) = (0, False, None) |
| 558 |
else: |
| 559 |
(offset, reverse, current_position) = self.cursor |
| 560 |
|
| 561 |
# Cursor pagination always enforces an ordering. |
| 562 |
if reverse: |
| 563 |
queryset = queryset.order_by(*_reverse_ordering(self.ordering)) |
| 564 |
else: |
| 565 |
queryset = queryset.order_by(*self.ordering) |
| 566 |
|
| 567 |
# If we have a cursor with a fixed position then filter by that. |
| 568 |
if current_position is not None: |
| 569 |
order = self.ordering[0] |
| 570 |
is_reversed = order.startswith('-') |
| 571 |
order_attr = order.lstrip('-') |
| 572 |
|
| 573 |
# Test for: (cursor reversed) XOR (queryset reversed) |
| 574 |
if self.cursor.reverse != is_reversed: |
| 575 |
kwargs = {order_attr + '__lt': current_position} |
| 576 |
else: |
| 577 |
kwargs = {order_attr + '__gt': current_position} |
| 578 |
|
| 579 |
queryset = queryset.filter(**kwargs) |
| 580 |
|
| 581 |
# If we have an offset cursor then offset the entire page by that amount. |
| 582 |
# We also always fetch an extra item in order to determine if there is a |
| 583 |
# page following on from this one. |
| 584 |
results = list(queryset[offset:offset + self.page_size + 1]) |
| 585 |
self.page = list(results[:self.page_size]) |
| 586 |
|
| 587 |
# Determine the position of the final item following the page. |
| 588 |
if len(results) > len(self.page): |
| 589 |
has_following_position = True |
| 590 |
following_position = self._get_position_from_instance(results[-1], self.ordering) |
| 591 |
else: |
| 592 |
has_following_position = False |
| 593 |
following_position = None |
| 594 |
|
| 595 |
if reverse: |
| 596 |
# If we have a reverse queryset, then the query ordering was in reverse |
| 597 |
# so we need to reverse the items again before returning them to the user. |
| 598 |
self.page = list(reversed(self.page)) |
| 599 |
|
| 600 |
# Determine next and previous positions for reverse cursors. |
| 601 |
self.has_next = (current_position is not None) or (offset > 0) |
| 602 |
self.has_previous = has_following_position |
| 603 |
if self.has_next: |
| 604 |
self.next_position = current_position |
| 605 |
if self.has_previous: |
| 606 |
self.previous_position = following_position |
| 607 |
else: |
| 608 |
# Determine next and previous positions for forward cursors. |
| 609 |
self.has_next = has_following_position |
| 610 |
self.has_previous = (current_position is not None) or (offset > 0) |
| 611 |
if self.has_next: |
| 612 |
self.next_position = following_position |
| 613 |
if self.has_previous: |
| 614 |
self.previous_position = current_position |
| 615 |
|
| 616 |
# Display page controls in the browsable API if there is more |
| 617 |
# than one page. |
| 618 |
if (self.has_previous or self.has_next) and self.template is not None: |
| 619 |
self.display_page_controls = True |
| 620 |
|
| 621 |
return self.page |
| 622 |
|
| 623 |
def get_page_size(self, request): |
| 624 |
if self.page_size_query_param: |
| 625 |
with contextlib.suppress(KeyError, ValueError): |
| 626 |
return _positive_int( |
| 627 |
request.query_params[self.page_size_query_param], |
| 628 |
strict=True, |
| 629 |
cutoff=self.max_page_size |
| 630 |
) |
| 631 |
return self.page_size |
| 632 |
|
| 633 |
def get_next_link(self): |
| 634 |
if not self.has_next: |
| 635 |
return None |
| 636 |
|
| 637 |
if self.page and self.cursor and self.cursor.reverse and self.cursor.offset != 0: |
| 638 |
# If we're reversing direction and we have an offset cursor |
| 639 |
# then we cannot use the first position we find as a marker. |
| 640 |
compare = self._get_position_from_instance(self.page[-1], self.ordering) |
| 641 |
else: |
| 642 |
compare = self.next_position |
| 643 |
offset = 0 |
| 644 |
|
| 645 |
has_item_with_unique_position = False |
| 646 |
for item in reversed(self.page): |
| 647 |
position = self._get_position_from_instance(item, self.ordering) |
| 648 |
if position != compare: |
| 649 |
# The item in this position and the item following it |
| 650 |
# have different positions. We can use this position as |
| 651 |
# our marker. |
| 652 |
has_item_with_unique_position = True |
| 653 |
break |
| 654 |
|
| 655 |
# The item in this position has the same position as the item |
| 656 |
# following it, we can't use it as a marker position, so increment |
| 657 |
# the offset and keep seeking to the previous item. |
| 658 |
compare = position |
| 659 |
offset += 1 |
| 660 |
|
| 661 |
if self.page and not has_item_with_unique_position: |
| 662 |
# There were no unique positions in the page. |
| 663 |
if not self.has_previous: |
| 664 |
# We are on the first page. |
| 665 |
# Our cursor will have an offset equal to the page size, |
| 666 |
# but no position to filter against yet. |
| 667 |
offset = self.page_size |
| 668 |
position = None |
| 669 |
elif self.cursor.reverse: |
| 670 |
# The change in direction will introduce a paging artifact, |
| 671 |
# where we end up skipping forward a few extra items. |
| 672 |
offset = 0 |
| 673 |
position = self.previous_position |
| 674 |
else: |
| 675 |
# Use the position from the existing cursor and increment |
| 676 |
# it's offset by the page size. |
| 677 |
offset = self.cursor.offset + self.page_size |
| 678 |
position = self.previous_position |
| 679 |
|
| 680 |
if not self.page: |
| 681 |
position = self.next_position |
| 682 |
|
| 683 |
cursor = Cursor(offset=offset, reverse=False, position=position) |
| 684 |
return self.encode_cursor(cursor) |
| 685 |
|
| 686 |
def get_previous_link(self): |
| 687 |
if not self.has_previous: |
| 688 |
return None |
| 689 |
|
| 690 |
if self.page and self.cursor and not self.cursor.reverse and self.cursor.offset != 0: |
| 691 |
# If we're reversing direction and we have an offset cursor |
| 692 |
# then we cannot use the first position we find as a marker. |
| 693 |
compare = self._get_position_from_instance(self.page[0], self.ordering) |
| 694 |
else: |
| 695 |
compare = self.previous_position |
| 696 |
offset = 0 |
| 697 |
|
| 698 |
has_item_with_unique_position = False |
| 699 |
for item in self.page: |
| 700 |
position = self._get_position_from_instance(item, self.ordering) |
| 701 |
if position != compare: |
| 702 |
# The item in this position and the item following it |
| 703 |
# have different positions. We can use this position as |
| 704 |
# our marker. |
| 705 |
has_item_with_unique_position = True |
| 706 |
break |
| 707 |
|
| 708 |
# The item in this position has the same position as the item |
| 709 |
# following it, we can't use it as a marker position, so increment |
| 710 |
# the offset and keep seeking to the previous item. |
| 711 |
compare = position |
| 712 |
offset += 1 |
| 713 |
|
| 714 |
if self.page and not has_item_with_unique_position: |
| 715 |
# There were no unique positions in the page. |
| 716 |
if not self.has_next: |
| 717 |
# We are on the final page. |
| 718 |
# Our cursor will have an offset equal to the page size, |
| 719 |
# but no position to filter against yet. |
| 720 |
offset = self.page_size |
| 721 |
position = None |
| 722 |
elif self.cursor.reverse: |
| 723 |
# Use the position from the existing cursor and increment |
| 724 |
# it's offset by the page size. |
| 725 |
offset = self.cursor.offset + self.page_size |
| 726 |
position = self.next_position |
| 727 |
else: |
| 728 |
# The change in direction will introduce a paging artifact, |
| 729 |
# where we end up skipping back a few extra items. |
| 730 |
offset = 0 |
| 731 |
position = self.next_position |
| 732 |
|
| 733 |
if not self.page: |
| 734 |
position = self.previous_position |
| 735 |
|
| 736 |
cursor = Cursor(offset=offset, reverse=True, position=position) |
| 737 |
return self.encode_cursor(cursor) |
| 738 |
|
| 739 |
def get_ordering(self, request, queryset, view): |
| 740 |
""" |
| 741 |
Return a tuple of strings, that may be used in an `order_by` method. |
| 742 |
""" |
| 743 |
# The default case is to check for an `ordering` attribute |
| 744 |
# on this pagination instance. |
| 745 |
ordering = self.ordering |
| 746 |
|
| 747 |
ordering_filters = [ |
| 748 |
filter_cls for filter_cls in getattr(view, 'filter_backends', []) |
| 749 |
if hasattr(filter_cls, 'get_ordering') |
| 750 |
] |
| 751 |
|
| 752 |
if ordering_filters: |
| 753 |
# If a filter exists on the view that implements `get_ordering` |
| 754 |
# then we defer to that filter to determine the ordering. |
| 755 |
filter_cls = ordering_filters[0] |
| 756 |
filter_instance = filter_cls() |
| 757 |
ordering_from_filter = filter_instance.get_ordering(request, queryset, view) |
| 758 |
if ordering_from_filter: |
| 759 |
ordering = ordering_from_filter |
| 760 |
|
| 761 |
assert ordering is not None, ( |
| 762 |
'Using cursor pagination, but no ordering attribute was declared ' |
| 763 |
'on the pagination class.' |
| 764 |
) |
| 765 |
assert '__' not in ordering, ( |
| 766 |
'Cursor pagination does not support double underscore lookups ' |
| 767 |
'for orderings. Orderings should be an unchanging, unique or ' |
| 768 |
'nearly-unique field on the model, such as "-created" or "pk".' |
| 769 |
) |
| 770 |
|
| 771 |
assert isinstance(ordering, (str, list, tuple)), ( |
| 772 |
'Invalid ordering. Expected string or tuple, but got {type}'.format( |
| 773 |
type=type(ordering).__name__ |
| 774 |
) |
| 775 |
) |
| 776 |
|
| 777 |
if isinstance(ordering, str): |
| 778 |
return (ordering,) |
| 779 |
return tuple(ordering) |
| 780 |
|
| 781 |
def decode_cursor(self, request): |
| 782 |
""" |
| 783 |
Given a request with a cursor, return a `Cursor` instance. |
| 784 |
""" |
| 785 |
# Determine if we have a cursor, and if so then decode it. |
| 786 |
encoded = request.query_params.get(self.cursor_query_param) |
| 787 |
if encoded is None: |
| 788 |
return None |
| 789 |
|
| 790 |
try: |
| 791 |
querystring = b64decode(encoded.encode('ascii')).decode('ascii') |
| 792 |
tokens = parse.parse_qs(querystring, keep_blank_values=True) |
| 793 |
|
| 794 |
offset = tokens.get('o', ['0'])[0] |
| 795 |
offset = _positive_int(offset, cutoff=self.offset_cutoff) |
| 796 |
|
| 797 |
reverse = tokens.get('r', ['0'])[0] |
| 798 |
reverse = bool(int(reverse)) |
| 799 |
|
| 800 |
position = tokens.get('p', [None])[0] |
| 801 |
except (TypeError, ValueError): |
| 802 |
raise NotFound(self.invalid_cursor_message) |
| 803 |
|
| 804 |
return Cursor(offset=offset, reverse=reverse, position=position) |
| 805 |
|
| 806 |
def encode_cursor(self, cursor): |
| 807 |
""" |
| 808 |
Given a Cursor instance, return an url with encoded cursor. |
| 809 |
""" |
| 810 |
tokens = {} |
| 811 |
if cursor.offset != 0: |
| 812 |
tokens['o'] = str(cursor.offset) |
| 813 |
if cursor.reverse: |
| 814 |
tokens['r'] = '1' |
| 815 |
if cursor.position is not None: |
| 816 |
tokens['p'] = cursor.position |
| 817 |
|
| 818 |
querystring = parse.urlencode(tokens, doseq=True) |
| 819 |
encoded = b64encode(querystring.encode('ascii')).decode('ascii') |
| 820 |
return replace_query_param(self.base_url, self.cursor_query_param, encoded) |
| 821 |
|
| 822 |
def _get_position_from_instance(self, instance, ordering): |
| 823 |
field_name = ordering[0].lstrip('-') |
| 824 |
if isinstance(instance, dict): |
| 825 |
attr = instance[field_name] |
| 826 |
else: |
| 827 |
attr = getattr(instance, field_name) |
| 828 |
return str(attr) |
| 829 |
|
| 830 |
def get_paginated_response(self, data): |
| 831 |
return Response({ |
| 832 |
'next': self.get_next_link(), |
| 833 |
'previous': self.get_previous_link(), |
| 834 |
'results': data, |
| 835 |
}) |
| 836 |
|
| 837 |
def get_paginated_response_schema(self, schema): |
| 838 |
return { |
| 839 |
'type': 'object', |
| 840 |
'required': ['results'], |
| 841 |
'properties': { |
| 842 |
'next': { |
| 843 |
'type': 'string', |
| 844 |
'nullable': True, |
| 845 |
'format': 'uri', |
| 846 |
'example': 'http://api.example.org/accounts/?{cursor_query_param}=cD00ODY%3D"'.format( |
| 847 |
cursor_query_param=self.cursor_query_param) |
| 848 |
}, |
| 849 |
'previous': { |
| 850 |
'type': 'string', |
| 851 |
'nullable': True, |
| 852 |
'format': 'uri', |
| 853 |
'example': 'http://api.example.org/accounts/?{cursor_query_param}=cj0xJnA9NDg3'.format( |
| 854 |
cursor_query_param=self.cursor_query_param) |
| 855 |
}, |
| 856 |
'results': schema, |
| 857 |
}, |
| 858 |
} |
| 859 |
|
| 860 |
def get_html_context(self): |
| 861 |
return { |
| 862 |
'previous_url': self.get_previous_link(), |
| 863 |
'next_url': self.get_next_link() |
| 864 |
} |
| 865 |
|
| 866 |
def to_html(self): |
| 867 |
template = loader.get_template(self.template) |
| 868 |
context = self.get_html_context() |
| 869 |
return template.render(context) |
| 870 |
|
| 871 |
def get_schema_operation_parameters(self, view): |
| 872 |
parameters = [ |
| 873 |
{ |
| 874 |
'name': self.cursor_query_param, |
| 875 |
'required': False, |
| 876 |
'in': 'query', |
| 877 |
'description': force_str(self.cursor_query_description), |
| 878 |
'schema': { |
| 879 |
'type': 'string', |
| 880 |
}, |
| 881 |
} |
| 882 |
] |
| 883 |
if self.page_size_query_param is not None: |
| 884 |
parameters.append( |
| 885 |
{ |
| 886 |
'name': self.page_size_query_param, |
| 887 |
'required': False, |
| 888 |
'in': 'query', |
| 889 |
'description': force_str(self.page_size_query_description), |
| 890 |
'schema': { |
| 891 |
'type': 'integer', |
| 892 |
}, |
| 893 |
} |
| 894 |
) |
| 895 |
return parameters |