1 from django import template
2 from django.db import models
3 from django.core.cache import cache
5 register = template.Library()
7 Chunk = models.get_model('chunks', 'chunk')
8 CACHE_PREFIX = "chunk_"
10 def do_get_chunk(parser, token):
11 # split_contents() knows not to split quoted strings.
12 tokens = token.split_contents()
13 if len(tokens) < 2 or len(tokens) > 3:
14 raise template.TemplateSyntaxError, "%r tag should have either 2 or 3 arguments" % (tokens[0],)
16 tag_name, key = tokens
19 tag_name, key, cache_time = tokens
20 # Check to see if the key is properly double/single quoted
21 if not (key[0] == key[-1] and key[0] in ('"', "'")):
22 raise template.TemplateSyntaxError, "%r tag's argument should be in quotes" % tag_name
23 # Send key without quotes and caching time
24 return ChunkNode(key[1:-1], cache_time)
26 class ChunkNode(template.Node):
27 def __init__(self, key, cache_time=0):
29 self.cache_time = cache_time
31 def render(self, context):
33 cache_key = CACHE_PREFIX + self.key
34 c = cache.get(cache_key)
36 c = Chunk.objects.get(key=self.key)
37 cache.set(cache_key, c, int(self.cache_time))
39 except Chunk.DoesNotExist:
40 n = Chunk(key=self.key)
45 register.tag('chunk', do_get_chunk)