Ticket #5691: 5691.2.patch

File 5691.2.patch, 7.3 KB (added by aaloy, 15 years ago)

Patch documentation

  • django/utils/cache.py

     
    2929from django.utils.encoding import smart_str, iri_to_uri
    3030from django.utils.http import http_date
    3131from django.utils.hashcompat import md5_constructor
     32from django.utils import translation
    3233from django.http import HttpRequest
    3334
    3435cc_delim_re = re.compile(r'\s*,\s*')
     
    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                key_prefix, path.hexdigest(), ctx.hexdigest())
     149    cache_key = 'views.decorators.cache.cache_page.%s.%s.%s' % (
     150        key_prefix, path.hexdigest(), ctx.hexdigest())
     151    if settings.USE_I18N:
     152        cache_key += ".%s" % translation.get_language()
     153    return cache_key
    150154
    151155def _generate_cache_header_key(key_prefix, request):
    152156    """Returns a cache key for the header cache."""
     
    166170    if key_prefix is None:
    167171        key_prefix = settings.CACHE_MIDDLEWARE_KEY_PREFIX
    168172    cache_key = _generate_cache_header_key(key_prefix, request)
     173    if settings.USE_I18N:
     174        cache_key += ".%s" % translation.get_language()
    169175    headerlist = cache.get(cache_key, None)
    170176    if headerlist is not None:
    171177        return _generate_cache_key(request, headerlist, key_prefix)
     
    190196    if cache_timeout is None:
    191197        cache_timeout = settings.CACHE_MIDDLEWARE_SECONDS
    192198    cache_key = _generate_cache_header_key(key_prefix, request)
     199    if settings.USE_I18N:
     200        cache_key += ".%s" % translation.get_language()
    193201    if response.has_header('Vary'):
    194202        headerlist = ['HTTP_'+header.upper().replace('-', '_')
    195203                      for header in cc_delim_re.split(response['Vary'])]
  • tests/regressiontests/cache/tests.py

     
    1414from django.core.cache import get_cache
    1515from django.core.cache.backends.base import InvalidCacheBackendError
    1616from django.http import HttpResponse, HttpRequest
     17from django.middleware.cache import FetchFromCacheMiddleware, UpdateCacheMiddleware
     18from django.utils import translation
    1719from django.utils.cache import patch_vary_headers, get_cache_key, learn_cache_key
    1820from django.utils.hashcompat import md5_constructor
    1921from regressiontests.cache.models import Poll, expensive_calculation
     
    458460        learn_cache_key(request, response)
    459461        self.assertEqual(get_cache_key(request), 'views.decorators.cache.cache_page.settingsprefix.a8c87a3d8c44853d7f79474f7ffe4ad5.d41d8cd98f00b204e9800998ecf8427e')
    460462
     463class CacheI18nTest(unittest.TestCase):
     464    def setUp(self): 
     465        self.orig_cache_middleware_seconds = settings.CACHE_MIDDLEWARE_SECONDS
     466        self.orig_cache_middleware_key_prefix = settings.CACHE_MIDDLEWARE_KEY_PREFIX
     467        self.orig_cache_backend = settings.CACHE_BACKEND
     468        self.orig_use_i18n = settings.USE_I18N
     469        self.orig_languages =  settings.LANGUAGES
     470 
     471        settings.LANGUAGES = (
     472                ('en', 'English'),
     473                ('es', 'Spanish'),
     474        )
     475        self.path = '/cache/test/'
     476        settings.CACHE_MIDDLEWARE_KEY_PREFIX = 'settingsprefix'
     477        settings.CACHE_MIDDLEWARE_SECONDS
     478        self.path = '/cache/test/'
     479       
     480 
     481    def tearDown(self):
     482        settings.CACHE_MIDDLEWARE_SECONDS = self.orig_cache_middleware_seconds
     483        settings.CACHE_MIDDLEWARE_KEY_PREFIX = self.orig_cache_middleware_key_prefix
     484        settings.CACHE_BACKEND = self.orig_cache_backend
     485        settings.USE_I18N = self.orig_use_i18n
     486        settings.LANGUAGES = self.orig_languages
     487        translation.deactivate()
     488 
     489    def _get_request(self):
     490        request = HttpRequest()
     491        request.META = {
     492            'SERVER_NAME': 'testserver',
     493            'SERVER_PORT': 80,
     494        }
     495        request.path = request.path_info = self.path
     496        return request
     497 
     498    def _get_request_cache(self):
     499        request = HttpRequest()
     500        request.META = {
     501            'SERVER_NAME': 'testserver',
     502            'SERVER_PORT': 80,
     503        }
     504        request.path = request.path_info = self.path
     505        request._cache_update_cache = True
     506        request.method = 'GET'
     507        request.session = {}
     508        return request
     509 
     510    def test_cache_key_i18n(self):
     511        settings.USE_I18N = True
     512        request = self._get_request()
     513        lang = translation.get_language()
     514        response = HttpResponse()
     515        key = learn_cache_key(request, response)
     516        self.assertTrue(key.endswith(lang), "Cache keys should include the language name when i18n is active")
     517        key2 = get_cache_key(request)
     518        self.assertEqual(key, key2)
     519 
     520    def test_cache_key_no_i18n (self):
     521        settings.USE_I18N = False
     522        request = self._get_request()
     523        lang = translation.get_language()
     524        response = HttpResponse()
     525        key = learn_cache_key(request, response)
     526        self.assertFalse(key.endswith(lang), "Cache keys shouldn't include the language name when i18n is inactive")
     527 
     528    def test_middleware(self):
     529 
     530        def set_cache(request, lang, msg):
     531            translation.activate(lang)
     532            response = HttpResponse()
     533            response.content= msg
     534            return UpdateCacheMiddleware().process_response(request, response)
     535 
     536        settings.CACHE_MIDDLEWARE_SECONDS = 60
     537        settings.CACHE_MIDDLEWARE_KEY_PREFIX="test"
     538        settings.CACHE_BACKEND='locmem:///'
     539        settings.USE_I18N = True
     540        en_message ="Hello world!"
     541        es_message ="Hola mundo!"
     542 
     543        request = self._get_request_cache()
     544        set_cache(request, 'en', en_message)
     545        get_cache_data = FetchFromCacheMiddleware().process_request(request)
     546        # Check that we can recover the cache
     547        self.assertNotEqual(get_cache_data.content, None)
     548        self.assertEqual(en_message, get_cache_data.content)
     549        # change the session language and set content
     550        request = self._get_request_cache()
     551        set_cache(request, 'es', es_message)
     552        # change again the language
     553        translation.activate('en')
     554        # retrieve the content from cache
     555        get_cache_data = FetchFromCacheMiddleware().process_request(request)
     556        self.assertEqual(get_cache_data.content, en_message)
     557        # change again the language
     558        translation.activate('es')
     559        get_cache_data = FetchFromCacheMiddleware().process_request(request)
     560        self.assertEqual(get_cache_data.content, es_message)
     561
    461562if __name__ == '__main__':
    462563    unittest.main()
  • docs/topics/cache.txt

     
    320320the ``never_cache`` decorator). See the `using other headers`__ section for
    321321more on these decorators.
    322322
     323.. versionadded:: 1.2
     324
     325If USE_I18N is set to True the generated cache key would include the language name.
     326
    323327__ `Controlling cache: Using other headers`_
    324328
    325329The per-view cache
Back to Top