From 1c4a2b47900d615e4e126cca93724a03fcec90b6 Mon Sep 17 00:00:00 2001 From: Ben Thorner Date: Mon, 30 May 2022 16:00:48 +0100 Subject: [PATCH] Cache templates and folders in TemplateList This gives us the performance gains identified in [^1] for the test service described in the spike: - user_template_folders - from 10s to a little above 3s on its own - get_templates_and_folders - from 10s to below 6s on its own In combination, these two uses of caching reduce the test page load time from 10s to a little above 3s. This is slightly higher than in the spike PR due to all the extra work we're doing to generate the "move to" list of folders, as described in a previous commit. The render time is unchanged for services with few folders. We start to see the benefit of this change at around 200 templates + folders, with no evidence that any service will experience worse render times, despite the extra work we're doing from previous commits. [^1]: https://github.com/alphagov/notifications-admin/pull/4251 --- app/models/template_list.py | 16 +++++++++++----- 1 file changed, 11 insertions(+), 5 deletions(-) diff --git a/app/models/template_list.py b/app/models/template_list.py index c077b0dc0..cfdff1f11 100644 --- a/app/models/template_list.py +++ b/app/models/template_list.py @@ -1,3 +1,5 @@ +from werkzeug.utils import cached_property + from app import format_notification_type @@ -16,10 +18,13 @@ class TemplateList(): self.user = user def __iter__(self): - for item in self.get_templates_and_folders( + yield from self.items + + @cached_property + def items(self): + return list(self.get_templates_and_folders( self.template_type, self.template_folder_id, ancestors=[] - ): - yield item + )) def get_templates_and_folders(self, template_type, template_folder_id, ancestors): @@ -67,7 +72,8 @@ class TemplateList(): and template.get('folder') == template_folder_id ] - def get_user_template_folders(self): + @cached_property + def user_template_folders(self): """Returns a modified list of folders a user has permission to view For each folder, we do the following: @@ -110,7 +116,7 @@ class TemplateList(): def get_template_folders(self, template_type='all', parent_folder_id=None): if self.user: - folders = self.get_user_template_folders() + folders = self.user_template_folders else: folders = self.service.all_template_folders if parent_folder_id: