Ticket #5691: 5691-use-lan-for-cache-key-r10338.diff

File 5691-use-lan-for-cache-key-r10338.diff, 7.8 KB (added by ramiro, 6 years ago)

Updated patch to port-r10335 and simplified tests

  • django/utils/cache.py

    diff -r 22012da61ff2 django/utils/cache.py
    a b  
    3030from django.utils.http import http_date
    3131from django.utils.hashcompat import md5_constructor
    3232from django.http import HttpRequest
     33from django.utils import translation
    3334
    3435cc_delim_re = re.compile(r'\s*,\s*')
    3536
     
    145146        if value is not None:
    146147            ctx.update(value)
    147148    path = md5_constructor(iri_to_uri(request.path))
    148     return 'views.decorators.cache.cache_page.%s.%s.%s' % (
     149    cache_key = 'views.decorators.cache.cache_page.%s.%s.%s' % (
    149150               key_prefix, path.hexdigest(), ctx.hexdigest())
     151
     152    if settings.USE_I18N:
     153        cache_key += ".%s" % translation.get_language()
     154
     155    return cache_key
    150156
    151157def _generate_cache_header_key(key_prefix, request):
    152158    """Returns a cache key for the header cache."""
     
    166172    if key_prefix is None:
    167173        key_prefix = settings.CACHE_MIDDLEWARE_KEY_PREFIX
    168174    cache_key = _generate_cache_header_key(key_prefix, request)
     175
     176    if settings.USE_I18N:
     177        cache_key += ".%s" % translation.get_language()
     178
    169179    headerlist = cache.get(cache_key, None)
    170180    if headerlist is not None:
    171181        return _generate_cache_key(request, headerlist, key_prefix)
     
    190200    if cache_timeout is None:
    191201        cache_timeout = settings.CACHE_MIDDLEWARE_SECONDS
    192202    cache_key = _generate_cache_header_key(key_prefix, request)
     203
     204    if settings.USE_I18N:
     205        cache_key += ".%s" % translation.get_language()
     206
    193207    if response.has_header('Vary'):
    194208        headerlist = ['HTTP_'+header.upper().replace('-', '_')
    195209                      for header in cc_delim_re.split(response['Vary'])]
  • tests/regressiontests/cache/tests.py

    diff -r 22012da61ff2 tests/regressiontests/cache/tests.py
    a b  
    298298        self.path = '/cache/test/'
    299299        self.old_settings_key_prefix = settings.CACHE_MIDDLEWARE_KEY_PREFIX
    300300        self.old_middleware_seconds = settings.CACHE_MIDDLEWARE_SECONDS
     301        self.old_use_i18n = settings.USE_I18N
    301302        settings.CACHE_MIDDLEWARE_KEY_PREFIX = 'settingsprefix'
    302303        settings.CACHE_MIDDLEWARE_SECONDS = 1
     304        settings.USE_I18N = False
    303305
    304306    def tearDown(self):
    305307        settings.CACHE_MIDDLEWARE_KEY_PREFIX = self.old_settings_key_prefix
    306308        settings.CACHE_MIDDLEWARE_SECONDS = self.old_middleware_seconds
     309        settings.USE_I18N = self.old_use_i18n
    307310
    308311    def _get_request(self, path):
    309312        request = HttpRequest()
  • new file tests/regressiontests/cachei18n/__init__.py

    diff -r 22012da61ff2 tests/regressiontests/cachei18n/__init__.py
    - +  
     1#
  • new file tests/regressiontests/cachei18n/models.py

    diff -r 22012da61ff2 tests/regressiontests/cachei18n/models.py
    - +  
     1#
  • new file tests/regressiontests/cachei18n/tests.py

    diff -r 22012da61ff2 tests/regressiontests/cachei18n/tests.py
    - +  
     1# -*- coding: UTF-8 -*-
     2
     3from django.core.cache import get_cache
     4from django.core.cache.backends.filebased import CacheClass as FileCache
     5from django.http import HttpRequest
     6from django.http import HttpResponse
     7from django.utils import cache
     8from django.utils import translation
     9
     10import shutil
     11import tempfile
     12import unittest
     13from django.conf import settings
     14from django.middleware.cache import FetchFromCacheMiddleware, UpdateCacheMiddleware
     15
     16class CacheI18nTest(unittest.TestCase):
     17    def setUp(self):
     18        # Special-case the file cache so we can clean up after ourselves.
     19        if isinstance(cache, FileCache):
     20            self.cache_dir = tempfile.mkdtemp()
     21            self.cache = get_cache("file://%s" % self.cache_dir)
     22        else:
     23            self.cache_dir = None
     24            self.cache = cache
     25
     26        self.orig_cache_middleware_seconds = settings.CACHE_MIDDLEWARE_SECONDS
     27        self.orig_cache_middleware_key_prefix = settings.CACHE_MIDDLEWARE_KEY_PREFIX
     28        self.orig_cache_backend = settings.CACHE_BACKEND
     29        self.orig_use_i18n = settings.USE_I18N
     30        self.orig_languages =  settings.LANGUAGES
     31
     32        settings.LANGUAGES = (
     33                ('en', 'English'),
     34                ('es', 'Spanish'),
     35        )
     36
     37    def tearDown(self):
     38        if self.cache_dir is not None:
     39            shutil.rmtree(self.cache_dir)
     40
     41        settings.CACHE_MIDDLEWARE_SECONDS = self.orig_cache_middleware_seconds
     42        settings.CACHE_MIDDLEWARE_KEY_PREFIX = self.orig_cache_middleware_key_prefix
     43        settings.CACHE_BACKEND = self.orig_cache_backend
     44        settings.USE_I18N = self.orig_use_i18n
     45        settings.LANGUAGES = self.orig_languages
     46        translation.deactivate()
     47
     48    def _get_request(self):
     49        request = HttpRequest()
     50        request.META = {
     51            'SERVER_NAME': 'testserver',
     52            'SERVER_PORT': 80,
     53        }
     54        request.path = request.path_info = "/agenda/index/"
     55        return request
     56
     57    def _get_request_cache(self):
     58        request = HttpRequest()
     59        request.META = {
     60            'SERVER_NAME': 'testserver',
     61            'SERVER_PORT': 80,
     62        }
     63        request.path = request.path_info = "/agenda/index/"
     64        request._cache_update_cache = True
     65        request.method = 'GET'
     66        request.session = {}
     67        return request
     68
     69    def test_cache_key_i18n(self):
     70        settings.USE_I18N = True
     71        request = self._get_request()
     72        lang = translation.get_language()
     73        response = HttpResponse()
     74        key = cache.learn_cache_key(request, response)
     75        self.assertTrue(key.endswith(lang), "Cache keys should include the language name when i18n is active")
     76        key2 = cache.get_cache_key(request)
     77        self.assertEqual(key, key2)
     78
     79    def test_cache_key_no_i18n (self):
     80        settings.USE_I18N = False
     81        request = self._get_request()
     82        lang = translation.get_language()
     83        response = HttpResponse()
     84        key = cache.learn_cache_key(request, response)
     85        self.assertFalse(key.endswith(lang), "Cache keys shouldn't include the language name when i18n is inactive")
     86
     87    def test_middleware(self):
     88
     89        def set_cache(request, lang, msg):
     90            translation.activate(lang)
     91            response = HttpResponse()
     92            response.content= msg
     93            return UpdateCacheMiddleware().process_response(request, response)
     94
     95        settings.CACHE_MIDDLEWARE_SECONDS = 60
     96        settings.CACHE_MIDDLEWARE_KEY_PREFIX="test"
     97        settings.CACHE_BACKEND='locmem:///'
     98        settings.USE_I18N = True
     99        en_message ="Hello world!"
     100        es_message ="Hola mundo!"
     101
     102        request = self._get_request_cache()
     103        set_cache(request, 'en', en_message)
     104        get_cache_data = FetchFromCacheMiddleware().process_request(request)
     105        # Check that we can recover the cache
     106        self.assertNotEqual(get_cache_data.content, None)
     107        self.assertEqual(en_message, get_cache_data.content)
     108        # change the session language and set content
     109        request = self._get_request_cache()
     110        set_cache(request, 'es', es_message)
     111        # change again the language
     112        translation.activate('en')
     113        # retrieve the content from cache
     114        get_cache_data = FetchFromCacheMiddleware().process_request(request)
     115        self.assertEqual(get_cache_data.content, en_message)
     116        # change again the language
     117        translation.activate('es')
     118        get_cache_data = FetchFromCacheMiddleware().process_request(request)
     119        self.assertEqual(get_cache_data.content, es_message)
Back to Top