@@ -41,3 +41,41 @@ def _load_next_page(self, last_pagination_item):
4141 opts .sort , opts .filter = self ._options .sort , self ._options .filter
4242 current_item_list , last_pagination_item = self ._endpoint (opts )
4343 return current_item_list , last_pagination_item
44+
45+ class InternalPager (object ):
46+
47+ def __init__ (self , caller , * args , request_opts = None , ** kwargs ):
48+ self ._endpoint = caller
49+ self ._options = request_opts
50+ self ._funcargs = args
51+ self ._kwargs = kwargs
52+ # If we have options we could be starting on any page, backfill the count
53+ if self ._options :
54+ self ._count = ((self ._options .pagenumber - 1 ) * self ._options .pagesize )
55+ else :
56+ self ._count = 0
57+
58+ def __iter__ (self ):
59+ # Fetch the first page
60+ current_item_list , last_pagination_item = self ._endpoint (* self ._funcargs , ** self ._kwargs , req_options = self ._options )
61+
62+ # Get the rest on demand as a generator
63+ while self ._count < last_pagination_item .total_available :
64+ if len (current_item_list ) == 0 :
65+ current_item_list , last_pagination_item = self ._load_next_page (last_pagination_item )
66+
67+ try :
68+ yield current_item_list .pop (0 )
69+ self ._count += 1
70+
71+ except IndexError :
72+ # The total count on Server changed while fetching exit gracefully
73+ raise StopIteration
74+
75+ def _load_next_page (self , last_pagination_item ):
76+ next_page = last_pagination_item .page_number + 1
77+ opts = RequestOptions (pagenumber = next_page , pagesize = last_pagination_item .page_size )
78+ if self ._options is not None :
79+ opts .sort , opts .filter = self ._options .sort , self ._options .filter
80+ current_item_list , last_pagination_item = self ._endpoint (* self ._funcargs , ** self ._kwargs , req_options = opts )
81+ return current_item_list , last_pagination_item
0 commit comments