Login

Cache view by user (and anonymous)

Author:
rafaelsdm
Posted:
August 24, 2011
Language:
Python
Version:
1.0
Tags:
views cache decorator
Score:
1 (after 1 ratings)

Use this decorator in your views to cache HttpResponse per user, so each user has his own cache, instead of a shared one as from django.views.decorators.cache.cache_page does.

Add this to use: from somewhere import cache_per_user

@cache_per_user(ttl=3600, cache_post=False) def my_view(request): return HttpResponse("LOL %s"%(request.user))

All documentation inside the decorator are in brazilian portuguese, feel free to translate to english

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
# -*- encoding: utf-8 -*-
'''
Python >= 2.4
Django >= 1.0

Author: eu@rafaelsdm.com
'''
from django.core.cache import cache

def cache_per_user(ttl=None, prefix=None, cache_post=False):
    '''Decorador que faz cache da view pra cada usuario
    * ttl - Tempo de vida do cache, não enviar esse parametro significa que o
      cache vai durar até que o servidor reinicie ou decida remove-lo 
    * prefix - Prefixo a ser usado para armazenar o response no cache. Caso nao
      seja informado sera usado 'view_cache_'+function.__name__
    * cache_post - Informa se eh pra fazer cache de requisicoes POST
    * O cache para usuarios anonimos é compartilhado com todos
    * A chave do cache será uma das possiveis opcoes:
        '%s_%s'%(prefix, user.id)
        '%s_anonymous'%(prefix)
        'view_cache_%s_%s'%(function.__name__, user.id)
        'view_cache_%s_anonymous'%(function.__name__)
    '''
    def decorator(function):
        def apply_cache(request, *args, **kwargs):
            # Gera a parte do usuario que ficara na chave do cache
            if request.user.is_anonymous():
                user = 'anonymous'
            else:
                user = request.user.id

            # Gera a chave do cache
            if prefix:
                CACHE_KEY = '%s_%s'%(prefix, user)
            else:
                CACHE_KEY = 'view_cache_%s_%s'%(function.__name__, user)       

            # Verifica se pode fazer o cache do request
            if not cache_post and request.method == 'POST':
                can_cache = False
            else:
                can_cache = True

            if can_cache:
                response = cache.get(CACHE_KEY, None)
            else:
                response = None
                
            if not response:
                response = function(request, *args, **kwargs)
                if can_cache:
                    cache.set(CACHE_KEY, response, ttl)
            return response
        return apply_cache
    return decorator

More like this

  1. Language aware cache decorator by bartTC 5 years, 10 months ago
  2. Run and cache only one instance of a heavy request by farnsworth 4 years, 6 months ago
  3. limit view request rate decorator by anatoliy.larin 5 years, 9 months ago
  4. JSON decorator for views handling ajax requests by anilshanbhag 2 years, 2 months ago
  5. New view decorator to only cache pages for anonymous users by vaughnkoch 4 years, 4 months ago

Comments

Please login first before commenting.