Debian Codegraph @

src/globus_sdk/paging/jsonapi.py

raw
1 from __future__ import annotations
2
3 import typing as t
4 from urllib.parse import parse_qs, urlsplit
5
6 from .base import PageT, Paginator
7
8
9 class JSONAPIPaginator(Paginator[PageT]):
10 """
11 A paginator which uses the next link of a JSON:API response if present
12 to fetch more pages.
13
14 Assumes the next link only changes query parameters between calls to
15 `method` and that `method` supports a keyword argument of `query_params`
16 which those changed query parameters will be passed to.
17 """
18
19 _REQUIRES_METHOD_KWARGS = ("query_params",)
20
21 def _get_next_link(self, page: dict[str, t.Any]) -> str | None:
22 links = page.get("links")
23 if links:
24 next_link = links.get("next")
25 if isinstance(next_link, str):
26 return next_link
27 return None
28
29 def pages(self) -> t.Iterator[PageT]:
30 while True:
31 current_page = self.method(*self.client_args, **self.client_kwargs)
32 yield current_page
33
34 next_link = self._get_next_link(current_page)
35 if next_link:
36 next_link_query_params = parse_qs(urlsplit(next_link).query)
37 self.client_kwargs["query_params"] = next_link_query_params
38 else:
39 break