Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix paging by auto-detecting the page size #17

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 11 additions & 7 deletions fakturoid/paging.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,17 +6,17 @@
class PagedResource(object):
"""List adapter for paged resources. Returns sliceable lazy loaded object."""

def __init__(self, page_size=20):
def __init__(self):
self.pages = {}
self.page_size = page_size or 20
self.page_size = None
self.page_count = None

def load_page(self, n):
raise NotImplementedError("You must implement load_page method.")

def ensure_page_count(self):
if self.page_count is None:
# load any page to get page count from headers
def ensure_paging_info(self):
if self.page_count is None or self.page_size is None:
# load any page to get page count and page size
self.get_page(0)

def get_page(self, n):
Expand All @@ -31,11 +31,12 @@ def get_page(self, n):
raise IndexError('index out of range')

def __len__(self):
self.ensure_page_count()
self.ensure_paging_info()
return (self.page_size * (self.page_count - 1) +
len(self.get_page(self.page_count - 1)))

def __getitem__(self, key):
self.ensure_paging_info()
if isinstance(key, int):
if key < 0:
key = len(self) + key
Expand Down Expand Up @@ -64,7 +65,10 @@ def load_page(self, n):
response = self.model_api.session._get(self.endpoint, params=params)
if self.page_count is None:
self.page_count = response.get('page_count', n + 1)
return list(self.model_api.unpack(response))
objects = list(self.model_api.unpack(response))
if self.page_size is None:
self.page_size = len(objects)
return objects

def __unicode__(self):
# TODO print if loaded
Expand Down