controlable db cache decorator

 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
from django.shortcuts import render_to_response
from django.template import RequestContext
from django.http import HttpResponse
from django.conf import settings
from cache.models import Cache
def cache(type):
def decorator(func):
def wrapper(request, *args, **kwargs):
try:
number = kwargs['number']
except KeyError:
number = 0
if settings.CACHE_ENABLED:
print 'trying cache'
try:
cache = Cache.objects.get(doorway=request.doorway, type=type, number=number)
except Cache.DoesNotExist:
print 'page not in cache'
pass
else:
print 'page in cache'
return HttpResponse(cache.content)
output = func(request, *args, **kwargs)
if settings.CACHE_ENABLED:
Cache.objects.create(doorway=request.doorway, type=type, number=number,
content=output.content)
return output
return wrapper
return decorator