Fixed #19698 -- Cleared sites cache with signals

Thanks ddavies at nomensa.com for the report and the patch and
serdaroncode for reviewing the patch.
This commit is contained in:
Claude Paroz 2013-02-23 19:28:17 +01:00
parent bfd4a71d41
commit 98ab8e8876
2 changed files with 21 additions and 14 deletions

View File

@ -1,4 +1,5 @@
from django.db import models from django.db import models
from django.db.models.signals import pre_save, pre_delete
from django.utils.translation import ugettext_lazy as _ from django.utils.translation import ugettext_lazy as _
from django.utils.encoding import python_2_unicode_compatible from django.utils.encoding import python_2_unicode_compatible
@ -49,20 +50,6 @@ class Site(models.Model):
def __str__(self): def __str__(self):
return self.domain return self.domain
def save(self, *args, **kwargs):
super(Site, self).save(*args, **kwargs)
# Cached information will likely be incorrect now.
if self.id in SITE_CACHE:
del SITE_CACHE[self.id]
def delete(self):
pk = self.pk
super(Site, self).delete()
try:
del SITE_CACHE[pk]
except KeyError:
pass
@python_2_unicode_compatible @python_2_unicode_compatible
class RequestSite(object): class RequestSite(object):
@ -96,3 +83,16 @@ def get_current_site(request):
else: else:
current_site = RequestSite(request) current_site = RequestSite(request)
return current_site return current_site
def clear_site_cache(sender, **kwargs):
"""
Clears the cache (if primed) each time a site is saved or deleted
"""
instance = kwargs['instance']
try:
del SITE_CACHE[instance.pk]
except KeyError:
pass
pre_save.connect(clear_site_cache, sender=Site)
pre_delete.connect(clear_site_cache, sender=Site)

View File

@ -42,6 +42,13 @@ class SitesFrameworkTests(TestCase):
site = Site.objects.get_current() site = Site.objects.get_current()
self.assertEqual("Example site", site.name) self.assertEqual("Example site", site.name)
def test_delete_all_sites_clears_cache(self):
# When all site objects are deleted the cache should also
# be cleared and get_current() should raise a DoesNotExist.
self.assertIsInstance(Site.objects.get_current(), Site)
Site.objects.all().delete()
self.assertRaises(Site.DoesNotExist, Site.objects.get_current)
@override_settings(ALLOWED_HOSTS=['example.com']) @override_settings(ALLOWED_HOSTS=['example.com'])
def test_get_current_site(self): def test_get_current_site(self):
# Test that the correct Site object is returned # Test that the correct Site object is returned