pagination.py 905 B

123456789101112131415161718192021222324252627
  1. from rest_framework.pagination import CursorPagination
  2. from rest_framework.response import Response
  3. class LinkHeaderPagination(CursorPagination):
  4. """ Inform the user of pagination links via response headers, similar to
  5. what's described in
  6. https://developer.github.com/guides/traversing-with-pagination/.
  7. """
  8. def get_paginated_response(self, data):
  9. next_url = self.get_next_link()
  10. previous_url = self.get_previous_link()
  11. links = []
  12. for url, label in (
  13. (previous_url, "prev"),
  14. (next_url, "next"),
  15. ):
  16. if url is not None:
  17. links.append('<{}>; rel="{}"; results="true"'.format(url, label))
  18. else:
  19. links.append('<>; rel="{}"; results="false"'.format(label))
  20. headers = {"Link": ", ".join(links)} if links else {}
  21. return Response(data, headers=headers)