Added philo-root reversal caching to Node.construct_url.
authorStephen Burrows <stephen.r.burrows@gmail.com>
Mon, 27 Jun 2011 20:36:38 +0000 (16:36 -0400)
committerStephen Burrows <stephen.r.burrows@gmail.com>
Mon, 27 Jun 2011 20:36:38 +0000 (16:36 -0400)
philo/models/nodes.py

index 830f94a..7371a1d 100644 (file)
@@ -2,9 +2,11 @@ from inspect import getargspec
 import mimetypes
 from os.path import basename
 
+from django.conf import settings
 from django.contrib.contenttypes import generic
 from django.contrib.contenttypes.models import ContentType
 from django.contrib.sites.models import Site, RequestSite
+from django.core.cache import cache
 from django.core.exceptions import ValidationError
 from django.core.servers.basehttp import FileWrapper
 from django.core.urlresolvers import resolve, clear_url_caches, reverse, NoReverseMatch
@@ -24,6 +26,7 @@ __all__ = ('Node', 'View', 'MultiView', 'Redirect', 'File')
 
 
 _view_content_type_limiter = ContentTypeSubclassLimiter(None)
+CACHE_PHILO_ROOT = getattr(settings, "PHILO_CACHE_PHILO_ROOT", True)
 
 
 class Node(SlugTreeEntity):
@@ -71,6 +74,8 @@ class Node(SlugTreeEntity):
                
                Node urls will not contain a trailing slash unless a subpath is provided which ends with a trailing slash. Subpaths are expected to begin with a slash, as if returned by :func:`django.core.urlresolvers.reverse`.
                
+               Because this method will be called frequently and will always try to reverse ``philo-root``, the results of that reversal will be cached by default. This can be disabled by setting :setting:`PHILO_CACHE_PHILO_ROOT` to ``False``.
+               
                :meth:`construct_url` may raise the following exceptions:
                
                - :class:`NoReverseMatch` if "philo-root" is not reversable -- for example, if :mod:`philo.urls` is not included anywhere in your urlpatterns.
@@ -85,7 +90,14 @@ class Node(SlugTreeEntity):
                
                """
                # Try reversing philo-root first, since we can't do anything if that fails.
-               root_url = reverse('philo-root')
+               if CACHE_PHILO_ROOT:
+                       key = "CACHE_PHILO_ROOT__" + settings.ROOT_URLCONF
+                       root_url = cache.get(key)
+                       if root_url is None:
+                               root_url = reverse('philo-root')
+                               cache.set(key, root_url)
+               else:
+                       root_url = reverse('philo-root')
                
                try:
                        current_site = Site.objects.get_current()