-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathiterator.py
More file actions
63 lines (45 loc) · 1.56 KB
/
iterator.py
File metadata and controls
63 lines (45 loc) · 1.56 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
import logging
from abc import abstractmethod
logger = logging.getLogger('cterasdk.common')
class BaseAsyncIterator:
"""Abstract Asynchronous Iterator"""
def __init__(self, callback, parameter):
self._callback = callback
self._parameter = parameter
self._more = True
self._objects = []
def __aiter__(self):
return self
async def __anext__(self):
if self._objects:
return self.object
if self._more:
self._more, page = await self.page()
self._objects.extend(page)
if self._objects:
return self.object
logger.debug('Stopping iteration.')
raise StopAsyncIteration
@property
def object(self):
return self._objects.pop(0)
@abstractmethod
async def page(self):
raise NotImplementedError("Subclass must implemenet the 'page' function")
class QueryAsyncIterator(BaseAsyncIterator):
""" Asynchronous Objects Iterator """
async def page(self):
response = await self._callback(self._parameter)
self._parameter.increment()
return response.more, response.objects
class CursorAsyncIterator(BaseAsyncIterator):
def __init__(self, callback, parameter):
super().__init__(callback, parameter)
self._cursor = None
@property
def cursor(self):
return self._parameter.cursor
async def page(self):
response = await self._callback(self._parameter)
self._parameter.cursor = response.cursor
return response.more, response.objects