Refactor to make pagination reusable

The responses we get to paginated queries from the API are fairly
consistent, so we should be able to reuse the code that takes JSON
from the API and turns it into Python objects. This commits factors out
that code so that it is reusable (by inheriting from it).
This commit is contained in:
Chris Hill-Scott
2020-05-12 17:06:23 +01:00
parent ee720662e1
commit fc1ca3ab2f
2 changed files with 25 additions and 13 deletions

View File

@@ -41,3 +41,22 @@ class ModelList(SerialisedModelCollection):
def __init__(self, *args):
self.items = self.client_method(*args)
class PaginatedModelList(ModelList):
response_key = 'data'
def __init__(self, *args, page=None, **kwargs):
try:
self.current_page = int(page)
except TypeError:
self.current_page = 1
response = self.client_method(
*args,
**kwargs,
page=self.current_page,
)
self.items = response[self.response_key]
self.prev_page = response.get('links', {}).get('prev', None)
self.next_page = response.get('links', {}).get('next', None)