Team Ai
Datasetpublic

codekingpro/portable-devtools

sourceHugging Faceupdated 5mo agoView on Hugging Face
1likes14kdownloads
_pagination.py52 linesDownload Raw Back to utils
1# Copyright 2022-present, the HuggingFace Inc. team.2#3# Licensed under the Apache License, Version 2.0 (the "License");4# you may not use this file except in compliance with the License.5# You may obtain a copy of the License at6#7#     http://www.apache.org/licenses/LICENSE-2.08#9# Unless required by applicable law or agreed to in writing, software10# distributed under the License is distributed on an "AS IS" BASIS,11# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.12# See the License for the specific language governing permissions and13# limitations under the License.14"""Contains utilities to handle pagination on Huggingface Hub."""15 16from collections.abc import Iterable17 18import httpx19 20from . import get_session, hf_raise_for_status, http_backoff, logging21 22 23logger = logging.get_logger(__name__)24 25 26def paginate(path: str, params: dict, headers: dict) -> Iterable:27    """Fetch a list of models/datasets/spaces and paginate through results.28 29    This is using the same "Link" header format as GitHub.30    See:31    - https://requests.readthedocs.io/en/latest/api/#requests.Response.links32    - https://docs.github.com/en/rest/guides/traversing-with-pagination#link-header33    """34    session = get_session()35    r = session.get(path, params=params, headers=headers)36    hf_raise_for_status(r)37    yield from r.json()38 39    # Follow pages40    # Next link already contains query params41    next_page = _get_next_page(r)42    while next_page is not None:43        logger.debug(f"Pagination detected. Requesting next page: {next_page}")44        r = http_backoff("GET", next_page, headers=headers)45        hf_raise_for_status(r)46        yield from r.json()47        next_page = _get_next_page(r)48 49 50def _get_next_page(response: httpx.Response) -> str | None:51    return response.links.get("next", {}).get("url")52 
codekingpro/portable-devtools · Team Ai