From 780b9bb715e586d3154290bf563a78abf74586cf Mon Sep 17 00:00:00 2001 From: Chris Hill-Scott Date: Fri, 26 Oct 2018 11:47:42 +0100 Subject: [PATCH] Use cached property from werkzeug.utils MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit This means we can have a method on the service model which hits the API (or Redis) but can be called multiple times (within the context of a request) without making multiple network requests. It does this by storing the results of the method on the object’s internal `__dict__` the first time the method is called. --- app/notify_client/models.py | 11 ++++++----- tests/app/main/views/test_templates.py | 2 +- 2 files changed, 7 insertions(+), 6 deletions(-) diff --git a/app/notify_client/models.py b/app/notify_client/models.py index c3bf3749c..d51ddfdd1 100644 --- a/app/notify_client/models.py +++ b/app/notify_client/models.py @@ -2,6 +2,7 @@ from itertools import chain from flask import request, session from flask_login import AnonymousUserMixin, UserMixin +from werkzeug.utils import cached_property from app.utils import get_default_sms_sender @@ -319,20 +320,20 @@ class Service(): def has_permission(self, permission): return permission in self.permissions - @property + @cached_property def has_jobs(self): # Can’t import at top-level because app isn’t yet initialised from app import job_api_client return job_api_client.has_jobs(self.id) - @property + @cached_property def has_team_members(self): from app import user_api_client return user_api_client.get_count_of_users_with_permission( self.id, 'manage_service' ) > 1 - @property + @cached_property def templates(self): from app import service_api_client @@ -375,7 +376,7 @@ class Service(): def has_sms_templates(self): return len(self.templates_by_type('sms')) > 0 - @property + @cached_property def has_email_reply_to_address(self): from app import service_api_client return bool(service_api_client.get_reply_to_email_addresses( @@ -390,7 +391,7 @@ class Service(): def shouldnt_use_govuk_as_sms_sender(self): return self.organisation_type in {'local', 'nhs'} - @property + @cached_property def sms_sender_is_govuk(self): from app import service_api_client return get_default_sms_sender( diff --git a/tests/app/main/views/test_templates.py b/tests/app/main/views/test_templates.py index 6d90f47c3..6aaebb32b 100644 --- a/tests/app/main/views/test_templates.py +++ b/tests/app/main/views/test_templates.py @@ -131,7 +131,7 @@ def test_should_show_page_for_choosing_a_template( for index, expected_template in enumerate(expected_templates): assert template_links[index].text.strip() == expected_template - mock_get_service_templates.assert_called_with(SERVICE_ONE_ID) + mock_get_service_templates.assert_called_once_with(SERVICE_ONE_ID) def test_should_not_show_template_nav_if_only_one_type_of_template(