Skip to content

Commit

Permalink
Support the caches logic introduced in Django 1.7.
Browse files Browse the repository at this point in the history
  • Loading branch information
tim-schilling committed Nov 11, 2014
1 parent e18af06 commit 02e8ea1
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 3 deletions.
31 changes: 28 additions & 3 deletions debug_toolbar/panels/cache.py
Expand Up @@ -6,10 +6,18 @@

from django.conf import settings
from django.core import cache
from django.core.cache import cache as original_cache, get_cache as original_get_cache
from django.core.cache import (
cache as original_cache,
get_cache as original_get_cache)
from django.core.cache.backends.base import BaseCache
from django.dispatch import Signal
from django.utils.translation import ugettext_lazy as _, ungettext

try:
from django.core.cache import CacheHandler, caches as original_caches
except ImportError: # Django < 1.7
CacheHandler = None
original_caches = None
try:
from collections import OrderedDict
except ImportError:
Expand Down Expand Up @@ -119,6 +127,17 @@ def get_cache(*args, **kwargs):
return CacheStatTracker(original_get_cache(*args, **kwargs))


def get_cache_handler():
if CacheHandler is None:
return None

class CacheHandlerPatch(CacheHandler):
def __getitem__(self, alias):
actual_cache = super(CacheHandlerPatch, self).__getitem__(alias)
return CacheStatTracker(actual_cache)
return CacheHandlerPatch()


class CachePanel(Panel):
"""
Panel that displays the cache statistics.
Expand Down Expand Up @@ -197,11 +216,17 @@ def title(self):
def enable_instrumentation(self):
# This isn't thread-safe because cache connections aren't thread-local
# in Django, unlike database connections.
cache.cache = CacheStatTracker(original_cache)
cache.get_cache = get_cache
if CacheHandler is None:
cache.cache = CacheStatTracker(original_cache)
else:
cache.caches = get_cache_handler()

def disable_instrumentation(self):
cache.cache = original_cache
if CacheHandler is None:
cache.cache = original_cache
else:
cache.caches = original_caches
cache.get_cache = original_get_cache

def process_response(self, request, response):
Expand Down
9 changes: 9 additions & 0 deletions tests/panels/test_cache.py
Expand Up @@ -2,7 +2,9 @@

from __future__ import absolute_import, unicode_literals

import django
from django.core import cache
from django.utils.unittest import skipIf

from ..base import BaseTestCase

Expand All @@ -24,3 +26,10 @@ def test_recording(self):
cache.cache.get('foo')
cache.cache.delete('foo')
self.assertEqual(len(self.panel.calls), 3)

@skipIf(django.VERSION < (1, 7), "Caches was added in Django 1.7")
def test_recording_caches(self):
self.assertEqual(len(self.panel.calls), 0)
cache.cache.set('foo', 'bar')
cache.caches[cache.DEFAULT_CACHE_ALIAS].get('foo')
self.assertEqual(len(self.panel.calls), 2)

0 comments on commit 02e8ea1

Please sign in to comment.