diff --git a/cachalot/templatetags/__init__.py b/cachalot/templatetags/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/cachalot/templatetags/cachalot.py b/cachalot/templatetags/cachalot.py new file mode 100644 index 0000000..e900bd1 --- /dev/null +++ b/cachalot/templatetags/cachalot.py @@ -0,0 +1,18 @@ +from django.apps import apps +from django.template import Library + +from ..api import get_last_invalidation as get_last_invalidation_function + + +register = Library() + + +@register.assignment_tag +def get_last_invalidation(*tables_or_model_lookups, **kwargs): + tables_or_models = [] + for table_or_model_lookup in tables_or_model_lookups: + if '.' in table_or_model_lookup: + tables_or_models.append(apps.get_model(table_or_model_lookup)) + else: + tables_or_models.append(table_or_model_lookup) + return get_last_invalidation_function(*tables_or_models, **kwargs) diff --git a/cachalot/tests/api.py b/cachalot/tests/api.py index 1577d5c..d8b5514 100644 --- a/cachalot/tests/api.py +++ b/cachalot/tests/api.py @@ -9,6 +9,7 @@ from django.contrib.auth.models import User from django.core.cache import DEFAULT_CACHE_ALIAS from django.core.management import call_command from django.db import connection, transaction, DEFAULT_DB_ALIAS +from django.template import Template, Context from django.test import TransactionTestCase from ..api import * @@ -107,6 +108,38 @@ class APITestCase(TransactionTestCase): 'cachalot_test') self.assertAlmostEqual(timestamp, time(), delta=0.1) + def test_get_last_invalidation_template_tag(self): + original_timestamp = Template("{{ timestamp }}").render(Context({ + 'timestamp': get_last_invalidation('auth.Group', 'cachalot_test') + })) + + template = Template(""" + {% load cachalot %} + {% get_last_invalidation 'auth.Group' 'cachalot_test' as timestamp %} + {{ timestamp }} + """) + timestamp = template.render(Context()).strip() + + self.assertNotEqual(timestamp, '') + self.assertNotEqual(timestamp, '0.0') + self.assertAlmostEqual(float(timestamp), float(original_timestamp), + delta=0.1) + + template = Template(""" + {% load cachalot cache %} + {% get_last_invalidation 'auth.Group' 'cachalot_test' as timestamp %} + {% cache 10 cache_key_name timestamp %} + {{ content }} + {% endcache %} + """) + content = template.render(Context({'content': 'something'})).strip() + self.assertEqual(content, 'something') + content = template.render(Context({'content': 'anything'})).strip() + self.assertEqual(content, 'something') + invalidate('cachalot_test') + content = template.render(Context({'content': 'yet another'})).strip() + self.assertEqual(content, 'yet another') + class CommandTestCase(TransactionTestCase): multi_db = True