1 from debug_toolbar.panels import DebugPanel
2 try: from cStringIO import StringIO
3 except ImportError: import StringIO
4 from django.core import cache
5 from django.core.cache.backends.base import BaseCache
9 from django.template.loader import render_to_string
11 class CacheStatTracker(BaseCache):
12 """A small class used to track cache calls."""
13 def __init__(self, cache):
27 def _get_func_info(self):
28 stack = inspect.stack()[2]
29 return (os.path.basename(stack[1]), stack[2], stack[3], stack[4])
31 def get(self, key, default=None):
33 value = self.cache.get(key, default)
34 this_time = time.time()-t
35 self.total_time += this_time*1000
41 self.calls.append((this_time, 'get', (key,), self._get_func_info()))
44 def set(self, key, value, timeout=None):
46 self.cache.set(key, value, timeout)
47 this_time = time.time()-t
48 self.total_time += this_time*1000
50 self.calls.append((this_time, 'set', (key, value, timeout), self._get_func_info()))
52 def delete(self, key):
54 self.instance.delete(key, value)
55 this_time = time.time()-t
56 self.total_time += this_time*1000
58 self.calls.append((this_time, 'delete', (key,), self._get_func_info()))
60 def get_many(self, keys):
62 results = self.cache.get_many(keys)
63 this_time = time.time()-t
64 self.total_time += this_time*1000
66 for key, value in results.iteritems():
71 self.calls.append((this_time, 'get_many', (keys,), self._get_func_info()))
73 class CacheDebugPanel(DebugPanel):
75 Panel that displays the cache statistics.
79 def __init__(self, request):
80 # This is hackish but to prevent threading issues
82 if isinstance(cache.cache, CacheStatTracker):
84 self.cache = cache.cache
86 self.cache = CacheStatTracker(cache.cache)
87 cache.cache = self.cache
88 super(CacheDebugPanel, self).__init__(request)
91 return 'Cache: %.2fms' % self.cache.total_time
98 cache_calls = len(self.cache.calls),
99 cache_time = self.cache.total_time,
102 return render_to_string('debug_toolbar/panels/cache.html', context)