Ticket #3766: site_cache.diff

File site_cache.diff, 1.5 KB (added by Matt Riggott, 8 years ago)

Patch to add Site object caching to django.contrib.sites.models.SiteManager

  • django/trunk/django/contrib/sites/models.py

     
    11from django.db import models
    22from django.utils.translation import ugettext_lazy as _
    33
     4SITE_CACHE = {}
     5
    46class SiteManager(models.Manager):
    57    def get_current(self):
     8        """
     9        Returns the current ``Site`` based on the SITE_ID in the
     10        project's settings. The ``Site`` object is cached the first
     11        time it's retrieved from the database.
     12        """
    613        from django.conf import settings
    714        try:
    815            sid = settings.SITE_ID
    916        except AttributeError:
    1017            from django.core.exceptions import ImproperlyConfigured
    1118            raise ImproperlyConfigured("You're using the Django \"sites framework\" without having set the SITE_ID setting. Create a site in your database and set the SITE_ID setting to fix this error.")
    12         return self.get(pk=sid)
     19        try:
     20            current_site = SITE_CACHE[sid]
     21        except KeyError:
     22            current_site = self.get(pk=sid)
     23            SITE_CACHE[sid] = current_site
     24        return current_site
    1325
     26    def clear_cache(self):
     27        """Clears the ``Site`` object cache."""
     28        global SITE_CACHE
     29        SITE_CACHE = {}
     30
    1431class Site(models.Model):
    1532    domain = models.CharField(_('domain name'), max_length=100)
    1633    name = models.CharField(_('display name'), max_length=50)
Back to Top