From 3b5b958b78b63f2494d073aa1cc670a176cc55fd Mon Sep 17 00:00:00 2001 From: Christopher Neugebauer Date: Thu, 28 Apr 2016 17:19:27 +1000 Subject: [PATCH] =?UTF-8?q?Makes=20the=20discounts=20section=20from=20=5Fh?= =?UTF-8?q?andle=5Fproducts=20evaluate=20lazily,=20just=20in=20case=20it?= =?UTF-8?q?=E2=80=99s=20never=20displayed=20in=20a=20template=20(those=20a?= =?UTF-8?q?re=20some=20very=20very=20expensive=20queries=20there).?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- registrasion/util.py | 30 ++++++++++++++++++++++++++++++ registrasion/views.py | 6 +++++- 2 files changed, 35 insertions(+), 1 deletion(-) diff --git a/registrasion/util.py b/registrasion/util.py index 7179ceb5..54f56a1e 100644 --- a/registrasion/util.py +++ b/registrasion/util.py @@ -25,3 +25,33 @@ def all_arguments_optional(ntcls): ) return ntcls + + +def lazy(function, *args, **kwargs): + ''' Produces a callable so that functions can be lazily evaluated in + templates. + + Arguments: + + function (callable): The function to call at evaluation time. + + args: Positional arguments, passed directly to ``function``. + + kwargs: Keyword arguments, passed directly to ``function``. + + Return: + + callable: A callable that will evaluate a call to ``function`` with + the specified arguments. + + ''' + + NOT_EVALUATED = object() + retval = [NOT_EVALUATED] + + def evaluate(): + if retval[0] is NOT_EVALUATED: + retval[0] = function(*args, **kwargs) + return retval[0] + + return evaluate diff --git a/registrasion/views.py b/registrasion/views.py index e23b57a1..41c4a0d6 100644 --- a/registrasion/views.py +++ b/registrasion/views.py @@ -429,7 +429,11 @@ def _handle_products(request, category, products, prefix): ) handled = False if products_form.errors else True - discounts = DiscountController.available_discounts( + # Making this a function to lazily evaluate when it's displayed + # in templates. + + discounts = util.lazy( + DiscountController.available_discounts, request.user, [], products,