|
| 1 | +""" |
| 2 | +This module contains the PageIterator class which is used to |
| 3 | +iterate over paged responses from a server. |
| 4 | +
|
| 5 | +The PageIterator class provides methods to iterate over the items |
| 6 | +in the pages, fetch the next page, convert a response to a page, and |
| 7 | + fetch the next page from the server. |
| 8 | +
|
| 9 | +The PageIterator class uses the Parsable interface to parse the responses |
| 10 | + from the server, the HttpxRequestAdapter class to send requests to the |
| 11 | + server, and the PageResult class to represent the pages. |
| 12 | +
|
| 13 | +This module also imports the necessary types and exceptions from the |
| 14 | +typing, requests.exceptions, kiota_http.httpx_request_adapter, |
| 15 | + kiota_abstractions.method, kiota_abstractions.headers_collection, |
| 16 | +kiota_abstractions.request_information, kiota_abstractions.serialization.parsable, |
| 17 | +and models modules. |
| 18 | +""" |
| 19 | + |
| 20 | +from typing import Callable, Optional, Union, Dict, List |
| 21 | + |
| 22 | +from typing import TypeVar |
| 23 | +from requests.exceptions import InvalidURL |
| 24 | + |
| 25 | +from kiota_http.httpx_request_adapter import HttpxRequestAdapter |
| 26 | +from kiota_abstractions.method import Method |
| 27 | +from kiota_abstractions.headers_collection import HeadersCollection |
| 28 | +from kiota_abstractions.request_information import RequestInformation |
| 29 | +from kiota_abstractions.serialization.parsable import Parsable |
| 30 | + |
| 31 | +from msgraph_core.models.page_result import PageResult # pylint: disable=no-name-in-module, import-error |
| 32 | + |
| 33 | +T = TypeVar('T', bound=Parsable) |
| 34 | + |
| 35 | + |
| 36 | +class PageIterator: |
| 37 | + """ |
| 38 | +This class is used to iterate over paged responses from a server. |
| 39 | +
|
| 40 | +The PageIterator class provides methods to iterate over the items in the pages, |
| 41 | +fetch the next page, and convert a response to a page. |
| 42 | +
|
| 43 | +Attributes: |
| 44 | + request_adapter (HttpxRequestAdapter): The adapter used to send HTTP requests. |
| 45 | + pause_index (int): The index at which to pause iteration. |
| 46 | + headers (HeadersCollection): The headers to include in the HTTP requests. |
| 47 | + request_options (list): The options for the HTTP requests. |
| 48 | + current_page (PageResult): The current page of items. |
| 49 | + object_type (str): The type of the items in the pages. |
| 50 | + has_next (bool): Whether there are more pages to fetch. |
| 51 | +
|
| 52 | +Methods: |
| 53 | + __init__(response: Union[T, list, object], request_adapter: HttpxRequestAdapter, |
| 54 | + constructor_callable: Optional[Callable] = None): Initializes a new instance of |
| 55 | + the PageIterator class. |
| 56 | + """ |
| 57 | + |
| 58 | + def __init__( |
| 59 | + self, |
| 60 | + response: Union[T, list, object], |
| 61 | + request_adapter: HttpxRequestAdapter, |
| 62 | + constructor_callable: Optional[Callable] = None |
| 63 | + ): |
| 64 | + self.request_adapter = request_adapter |
| 65 | + |
| 66 | + if isinstance(response, Parsable) and not constructor_callable: |
| 67 | + parsable_factory = type(response) |
| 68 | + elif constructor_callable is None: |
| 69 | + parsable_factory = PageResult |
| 70 | + self.parsable_factory = parsable_factory |
| 71 | + self.pause_index = 0 |
| 72 | + self.headers: HeadersCollection = HeadersCollection() |
| 73 | + self.request_options = [] # type: ignore |
| 74 | + self.current_page = self.convert_to_page(response) |
| 75 | + self.object_type = self.current_page.value[ |
| 76 | + 0].__class__.__name__ if self.current_page.value else None |
| 77 | + page = self.current_page |
| 78 | + self._next_link = response.get('odata_next_link', '') if isinstance( |
| 79 | + response, dict |
| 80 | + ) else getattr(response, 'odata_next_link', '') |
| 81 | + self._delta_link = response.get('@odata.deltaLink', '') if isinstance( |
| 82 | + response, dict |
| 83 | + ) else getattr(response, '@odata.deltaLink', '') |
| 84 | + |
| 85 | + if page is not None: |
| 86 | + self.current_page = page |
| 87 | + self.has_next = bool(page.odata_next_link) |
| 88 | + |
| 89 | + def set_headers(self, headers: dict) -> HeadersCollection: |
| 90 | + """ |
| 91 | + Sets the headers for the HTTP requests. |
| 92 | + This method takes a dictionary of headers and adds them to the |
| 93 | + existing headers. |
| 94 | + Args: |
| 95 | + headers (dict): A dictionary of headers to add. The keys are the |
| 96 | + header names and the values are the header values. |
| 97 | + """ |
| 98 | + self.headers.add_all(**headers) |
| 99 | + |
| 100 | + @property |
| 101 | + def delta_link(self): |
| 102 | + return self._delta_link |
| 103 | + |
| 104 | + @property |
| 105 | + def next_link(self): |
| 106 | + return self._next_link |
| 107 | + |
| 108 | + def set_request_options(self, request_options: list) -> None: |
| 109 | + """ |
| 110 | + Sets the request options for the HTTP requests. |
| 111 | + Args: |
| 112 | + request_options (list): The request options to set. |
| 113 | + """ |
| 114 | + self.request_options = request_options |
| 115 | + |
| 116 | + async def iterate(self, callback: Callable) -> None: |
| 117 | + """ |
| 118 | + Iterates over the pages and applies a callback function to each item. |
| 119 | + The iteration stops when there are no more pages or the callback |
| 120 | + function returns False. |
| 121 | + Args: |
| 122 | + callback (Callable): The function to apply to each item. |
| 123 | + It should take one argument (the item) and return a boolean. |
| 124 | + """ |
| 125 | + while True: |
| 126 | + keep_iterating = self.enumerate(callback) |
| 127 | + if not keep_iterating: |
| 128 | + return |
| 129 | + next_page = await self.next() |
| 130 | + if not next_page: |
| 131 | + return |
| 132 | + self.current_page = next_page |
| 133 | + self.pause_index = 0 |
| 134 | + |
| 135 | + async def next(self) -> Optional[PageResult]: |
| 136 | + """ |
| 137 | + Fetches the next page of items. |
| 138 | + Returns: |
| 139 | + dict: The next page of items, or None if there are no more pages. |
| 140 | + """ |
| 141 | + if self.current_page is not None and not self.current_page.odata_next_link: |
| 142 | + return None |
| 143 | + response = await self.fetch_next_page() |
| 144 | + print(f"Response - {type(response)}") |
| 145 | + page: PageResult = PageResult(response.odata_next_link, response.value) # type: ignore |
| 146 | + return page |
| 147 | + |
| 148 | + @staticmethod |
| 149 | + def convert_to_page(response: Union[T, list, object]) -> PageResult: |
| 150 | + """ |
| 151 | + Converts a response to a PageResult. |
| 152 | + This method extracts the 'value' and 'odata_next_link' from the |
| 153 | + response and uses them to create a PageResult. |
| 154 | + Args: |
| 155 | + response (Union[T, list, object]): The response to convert. It can |
| 156 | + be a list, an object, or any other type. |
| 157 | + Returns: |
| 158 | + PageResult: The PageResult created from the response. |
| 159 | + Raises: |
| 160 | + ValueError: If the response is None or does not contain a 'value'. |
| 161 | + """ |
| 162 | + if not response: |
| 163 | + raise ValueError('Response cannot be null.') |
| 164 | + value = None |
| 165 | + if isinstance(response, list): |
| 166 | + value = response.value # type: ignore |
| 167 | + elif hasattr(response, 'value'): |
| 168 | + value = getattr(response, 'value') |
| 169 | + elif isinstance(response, object): |
| 170 | + value = getattr(response, 'value', []) |
| 171 | + if value is None: |
| 172 | + raise ValueError('The response does not contain a value.') |
| 173 | + parsable_page = response if isinstance(response, dict) else vars(response) |
| 174 | + next_link = parsable_page.get('odata_next_link', '') if isinstance( |
| 175 | + parsable_page, dict |
| 176 | + ) else getattr(parsable_page, 'odata_next_link', '') |
| 177 | + |
| 178 | + page: PageResult = PageResult(next_link, value) |
| 179 | + return page |
| 180 | + |
| 181 | + async def fetch_next_page(self) -> List[Parsable]: |
| 182 | + """ |
| 183 | + Fetches the next page of items from the server. |
| 184 | + Returns: |
| 185 | + dict: The response from the server. |
| 186 | + Raises: |
| 187 | + ValueError: If the current page does not contain a next link. |
| 188 | + InvalidURL: If the next link URL could not be parsed. |
| 189 | + """ |
| 190 | + |
| 191 | + next_link = self.current_page.odata_next_link |
| 192 | + if not next_link: |
| 193 | + raise ValueError('The response does not contain a nextLink.') |
| 194 | + if not next_link.startswith('http'): |
| 195 | + raise InvalidURL('Could not parse nextLink URL.') |
| 196 | + request_info = RequestInformation() |
| 197 | + request_info.http_method = Method.GET |
| 198 | + request_info.url = next_link |
| 199 | + request_info.headers = self.headers |
| 200 | + if self.request_options: |
| 201 | + request_info.add_request_options(*self.request_options) |
| 202 | + error_map: Dict[str, int] = {} |
| 203 | + response = await self.request_adapter.send_async( |
| 204 | + request_info, self.parsable_factory, error_map |
| 205 | + ) |
| 206 | + return response |
| 207 | + |
| 208 | + def enumerate(self, callback: Optional[Callable] = None) -> bool: |
| 209 | + """ |
| 210 | + Enumerates over the items in the current page and applies a |
| 211 | + callback function to each item. |
| 212 | + Args: |
| 213 | + callback (Callable, optional): The function to apply to each item. |
| 214 | + It should take one argument (the item) and return a boolean. |
| 215 | + Returns: |
| 216 | + bool: False if there are no items in the current page or the |
| 217 | + callback function returns False, True otherwise. |
| 218 | + """ |
| 219 | + keep_iterating = True |
| 220 | + page_items = self.current_page.value |
| 221 | + if not page_items: |
| 222 | + return False |
| 223 | + for i in range(self.pause_index, len(page_items)): |
| 224 | + keep_iterating = callback(page_items[i]) if callback is not None else True |
| 225 | + if not keep_iterating: |
| 226 | + self.pause_index = i + 1 |
| 227 | + break |
| 228 | + return keep_iterating |
0 commit comments