Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix cache invalidation #131

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 25 additions & 0 deletions dbtemplates/test_cases.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import os
import shutil
import tempfile
from unittest import mock

from django.conf import settings as django_settings
from django.core.cache.backends.base import BaseCache
Expand Down Expand Up @@ -151,3 +152,27 @@ def test_check_template_syntax(self):
def test_get_cache_name(self):
self.assertEqual(get_cache_key('name with spaces'),
'dbtemplates::name-with-spaces::1')

def test_cache_invalidation(self):
# Add t1 into the cache of site2
self.t1.sites.add(self.site2)
with mock.patch('django.contrib.sites.models.SiteManager.get_current',
return_value=self.site2):
result = loader.get_template("base.html").render()
self.assertEqual(result, 'base')

# Update content
self.t1.content = 'new content'
self.t1.save()
result = loader.get_template("base.html").render()
self.assertEqual(result, 'new content')

# Cache invalidation should work across sites.
# Site2 should see the new content.
with mock.patch('django.contrib.sites.models.SiteManager.get_current',
return_value=self.site2):
result = loader.get_template("base.html").render()
self.assertEqual(result, 'new content')



10 changes: 6 additions & 4 deletions dbtemplates/utils/cache.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,9 +21,10 @@ def get_cache_backend():
cache = get_cache_backend()


def get_cache_key(name):
current_site = Site.objects.get_current()
return f"dbtemplates::{slugify(name)}::{current_site.pk}"
def get_cache_key(name, site=None):
if site is None:
site = Site.objects.get_current()
return f"dbtemplates::{slugify(name)}::{site.pk}"


def get_cache_notfound_key(name):
Expand Down Expand Up @@ -57,4 +58,5 @@ def remove_cached_template(instance, **kwargs):
Called via Django's signals to remove cached templates, if the template
in the database was changed or deleted.
"""
cache.delete(get_cache_key(instance.name))
for site in instance.sites.all():
cache.delete(get_cache_key(instance.name, site=site))