From fc1ca3ab2fea8eb0f7625e7d32c49461bb2799d8 Mon Sep 17 00:00:00 2001 From: Chris Hill-Scott Date: Tue, 12 May 2020 17:06:23 +0100 Subject: [PATCH] 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). --- app/models/__init__.py | 19 +++++++++++++++++++ app/models/job.py | 19 ++++++------------- 2 files changed, 25 insertions(+), 13 deletions(-) diff --git a/app/models/__init__.py b/app/models/__init__.py index 791c4a0c8..0acd9a31a 100644 --- a/app/models/__init__.py +++ b/app/models/__init__.py @@ -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) diff --git a/app/models/job.py b/app/models/job.py index 65679f3aa..e5443262e 100644 --- a/app/models/job.py +++ b/app/models/job.py @@ -9,7 +9,7 @@ from notifications_utils.letter_timings import ( from notifications_utils.timezones import utc_string_to_aware_gmt_datetime from werkzeug.utils import cached_property -from app.models import JSONModel, ModelList +from app.models import JSONModel, ModelList, PaginatedModelList from app.notify_client.job_api_client import job_api_client from app.notify_client.notification_api_client import notification_api_client from app.notify_client.service_api_client import service_api_client @@ -25,6 +25,7 @@ class Job(JSONModel): ALLOWED_PROPERTIES = { 'id', 'service', + 'template_name', 'template_version', 'original_file_name', 'created_at', @@ -230,20 +231,12 @@ class ScheduledJobs(ImmediateJobs): client_method = job_api_client.get_scheduled_jobs -class PaginatedJobs(ImmediateJobs): - +class PaginatedJobs(PaginatedModelList, ImmediateJobs): client_method = job_api_client.get_page_of_jobs - def __init__(self, service_id, page=None): - try: - self.current_page = int(page) - except TypeError: - self.current_page = 1 - response = self.client_method(service_id, page=self.current_page) - self.items = response['data'] - self.prev_page = response.get('links', {}).get('prev', None) - self.next_page = response.get('links', {}).get('next', None) + def __init__(self, service_id, *, page=None): + super().__init__(service_id, page=page) -class PaginatedUploads(PaginatedJobs): +class PaginatedUploads(PaginatedModelList, ImmediateJobs): client_method = job_api_client.get_uploads