Ticket #13014: 13014.diff

File 13014.diff, 5.8 KB (added by Chris Beaven, 14 years ago)
  • django/templatetags/cache.py

    diff --git a/django/templatetags/cache.py b/django/templatetags/cache.py
    index 387dd87..1b1b2be 100644
    a b  
    11from django.template import Library, Node, TemplateSyntaxError, Variable, VariableDoesNotExist
    22from django.template import resolve_variable
    33from django.core.cache import cache
    4 from django.utils.encoding import force_unicode
    5 from django.utils.http import urlquote
    6 from django.utils.hashcompat import md5_constructor
     4from django.utils.cache import get_template_cache_key
    75
    86register = Library()
    97
    class CacheNode(Node):  
    2422        except (ValueError, TypeError):
    2523            raise TemplateSyntaxError('"cache" tag got a non-integer timeout value: %r' % expire_time)
    2624        # Build a unicode key for this fragment and all vary-on's.
    27         args = md5_constructor(u':'.join([urlquote(resolve_variable(var, context)) for var in self.vary_on]))
    28         cache_key = 'template.cache.%s.%s' % (self.fragment_name, args.hexdigest())
     25        args = [resolve_variable(var, context) for var in self.vary_on]
     26        cache_key = get_template_cache_key(self.fragment_name, args)
    2927        value = cache.get(cache_key)
    3028        if value is None:
    3129            value = self.nodelist.render(context)
  • django/utils/cache.py

    diff --git a/django/utils/cache.py b/django/utils/cache.py
    index 6cfd893..4c360f6 100644
    a b import time  
    2323from django.conf import settings
    2424from django.core.cache import cache
    2525from django.utils.encoding import smart_str, iri_to_uri
    26 from django.utils.http import http_date
     26from django.utils.http import http_date, urlquote
    2727from django.utils.hashcompat import md5_constructor
    2828from django.utils.translation import get_language
    29 from django.http import HttpRequest
    3029
    3130cc_delim_re = re.compile(r'\s*,\s*')
    3231
    def patch_vary_headers(response, newheaders):  
    135134    response['Vary'] = ', '.join(vary_headers + additional_headers)
    136135
    137136def _i18n_cache_key_suffix(request, cache_key):
    138     """If enabled, returns the cache key ending with a locale."""
     137    """
     138    If I18N is enabled, returns the cache key appended with a locale (otherwise
     139    returns the cache key unmodified).
     140
     141    While ``request`` is a required argument, if it does not make sense in the
     142    context of the key generation, use ``None`` for its value.
     143
     144    """
    139145    if settings.USE_I18N:
    140146        # first check if LocaleMiddleware or another middleware added
    141147        # LANGUAGE_CODE to request, then fall back to the active language
    def learn_cache_key(request, response, cache_timeout=None, key_prefix=None):  
    210216        cache.set(cache_key, [], cache_timeout)
    211217        return _generate_cache_key(request, [], key_prefix)
    212218
     219def get_template_cache_key(name, args=None):
     220    """Returns a cache key for a template tag related cache."""
     221    args = args and [urlquote(arg) for arg in args] or []
     222    md5_args = md5_constructor(u':'.join(args))
     223    cache_key = 'template.cache.%s.%s' % (name, md5_args.hexdigest())
     224    return _i18n_cache_key_suffix(request=None, cache_key=cache_key)
    213225
    214226def _to_tuple(s):
    215227    t = s.split('=',1)
  • tests/regressiontests/cache/tests.py

    diff --git a/tests/regressiontests/cache/tests.py b/tests/regressiontests/cache/tests.py
    index 109374c..09ce616 100644
    a b from django.core.cache.backends.base import InvalidCacheBackendError  
    1616from django.http import HttpResponse, HttpRequest
    1717from django.middleware.cache import FetchFromCacheMiddleware, UpdateCacheMiddleware
    1818from django.utils import translation
    19 from django.utils.cache import patch_vary_headers, get_cache_key, learn_cache_key
     19from django.utils.cache import patch_vary_headers, get_cache_key, learn_cache_key,\
     20    get_template_cache_key
    2021from django.utils.hashcompat import md5_constructor
     22from django.template import Context
     23from django.template.loader import get_template_from_string
    2124from regressiontests.cache.models import Poll, expensive_calculation
    2225
    2326# functions/classes for complex data type tests
    class CacheI18nTest(unittest.TestCase):  
    527530        key2 = get_cache_key(request)
    528531        self.assertEqual(key, key2)
    529532
    530     def test_cache_key_no_i18n (self):
     533    def test_cache_key_no_i18n(self):
    531534        settings.USE_I18N = False
    532535        request = self._get_request()
    533536        lang = translation.get_language()
    class CacheI18nTest(unittest.TestCase):  
    568571        get_cache_data = FetchFromCacheMiddleware().process_request(request)
    569572        self.assertEqual(get_cache_data.content, es_message)
    570573
     574    def test_template_cache_key_i18n(self):
     575        settings.USE_I18N = True
     576        lang = 'en'
     577        translation.activate(lang)
     578        key = get_template_cache_key('somekey')
     579        self.assertTrue(key.endswith(lang), "Cache keys should include the "
     580                        "language name when i18n is active")
     581
     582    def test_template_cache_key_no_i18n(self):
     583        settings.USE_I18N = False
     584        lang = 'en'
     585        translation.activate(lang)
     586        key = get_template_cache_key('somekey')
     587        self.assertFalse(key.endswith(lang), "Cache keys shouldn't include "
     588                         "the language name when i18n is inactive")
     589
     590    def test_template_tag(self):
     591        settings.USE_I18N = True
     592        template = get_template_from_string('{% load cache %}'
     593                    '{% cache 60 greeting %}{{ welcome }}!{% endcache %}')
     594        translation.activate('en')
     595        template.render(Context({'welcome': 'Hello'}))
     596        translation.activate('es')
     597        template.render(Context({'welcome': 'Hola'}))
     598
     599        translation.activate('en')
     600        self.assertEqual(template.render(Context()), 'Hello!')
     601        translation.activate('es')
     602        self.assertEqual(template.render(Context()), 'Hola!')
     603
    571604if __name__ == '__main__':
    572605    unittest.main()
Back to Top