-
Notifications
You must be signed in to change notification settings - Fork 267
Expand file tree
/
Copy pathpagination.py
More file actions
77 lines (59 loc) · 1.81 KB
/
pagination.py
File metadata and controls
77 lines (59 loc) · 1.81 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
from typing import (
TYPE_CHECKING,
AsyncGenerator,
Awaitable,
Callable,
Generator,
Generic,
List,
Optional,
TypeVar,
Union,
)
import pydantic
from replicate.resource import Resource
T = TypeVar("T", bound=Resource)
if TYPE_CHECKING:
pass
class Page(pydantic.BaseModel, Generic[T]): # type: ignore
"""
A page of results from the API.
"""
previous: Optional[str] = None
"""A pointer to the previous page of results"""
next: Optional[str] = None
"""A pointer to the next page of results"""
results: List[T]
"""The results on this page"""
def __iter__(self): # noqa: ANN204
return iter(self.results)
def __getitem__(self, index: int) -> T:
return self.results[index]
def __len__(self) -> int:
return len(self.results)
def paginate(
list_method: Callable[[Union[str, "ellipsis", None]], Page[T]], # noqa: F821
) -> Generator[Page[T], None, None]:
"""
Iterate over all items using the provided list method.
Args:
list_method: A method that takes a cursor argument and returns a Page of items.
"""
cursor: Union[str, "ellipsis", None] = ... # noqa: F821
while cursor is not None:
page = list_method(cursor)
yield page
cursor = page.next
async def async_paginate(
list_method: Callable[[Union[str, "ellipsis", None]], Awaitable[Page[T]]], # noqa: F821
) -> AsyncGenerator[Page[T], None]:
"""
Asynchronously iterate over all items using the provided list method.
Args:
list_method: An async method that takes a cursor argument and returns a Page of items.
"""
cursor: Union[str, "ellipsis", None] = ... # noqa: F821
while cursor is not None:
page = await list_method(cursor)
yield page
cursor = page.next