_pagination.py 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. # coding=utf-8
  2. # Copyright 2022-present, the HuggingFace Inc. team.
  3. #
  4. # Licensed under the Apache License, Version 2.0 (the "License");
  5. # you may not use this file except in compliance with the License.
  6. # You may obtain a copy of the License at
  7. #
  8. # http://www.apache.org/licenses/LICENSE-2.0
  9. #
  10. # Unless required by applicable law or agreed to in writing, software
  11. # distributed under the License is distributed on an "AS IS" BASIS,
  12. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. # See the License for the specific language governing permissions and
  14. # limitations under the License.
  15. """Contains utilities to handle pagination on Huggingface Hub."""
  16. from typing import Dict, Iterable, Optional
  17. import requests
  18. from . import get_session, hf_raise_for_status, http_backoff, logging
  19. logger = logging.get_logger(__name__)
  20. def paginate(path: str, params: Dict, headers: Dict) -> Iterable:
  21. """Fetch a list of models/datasets/spaces and paginate through results.
  22. This is using the same "Link" header format as GitHub.
  23. See:
  24. - https://requests.readthedocs.io/en/latest/api/#requests.Response.links
  25. - https://docs.github.com/en/rest/guides/traversing-with-pagination#link-header
  26. """
  27. session = get_session()
  28. r = session.get(path, params=params, headers=headers)
  29. hf_raise_for_status(r)
  30. yield from r.json()
  31. # Follow pages
  32. # Next link already contains query params
  33. next_page = _get_next_page(r)
  34. while next_page is not None:
  35. logger.debug(f"Pagination detected. Requesting next page: {next_page}")
  36. r = http_backoff("GET", next_page, max_retries=20, retry_on_status_codes=429, headers=headers)
  37. hf_raise_for_status(r)
  38. yield from r.json()
  39. next_page = _get_next_page(r)
  40. def _get_next_page(response: requests.Response) -> Optional[str]:
  41. return response.links.get("next", {}).get("url")