1 from django import template
2 from django.db import models
3 from django.core.cache import cache
6 register = template.Library()
8 Chunk = models.get_model('chunks', 'chunk')
9 Attachment = models.get_model('chunks', 'attachment')
12 def do_get_chunk(parser, token):
13 # split_contents() knows not to split quoted strings.
14 tokens = token.split_contents()
15 if len(tokens) < 2 or len(tokens) > 3:
16 raise template.TemplateSyntaxError, "%r tag should have either 2 or 3 arguments" % (tokens[0],)
18 tag_name, key = tokens
21 tag_name, key, cache_time = tokens
22 # Check to see if the key is properly double/single quoted
23 if not (key[0] == key[-1] and key[0] in ('"', "'")):
24 raise template.TemplateSyntaxError, "%r tag's argument should be in quotes" % tag_name
25 # Send key without quotes and caching time
26 return ChunkNode(key[1:-1], cache_time)
29 class ChunkNode(template.Node):
30 def __init__(self, key, cache_time=0):
32 self.cache_time = cache_time
34 def render(self, context):
36 cache_key = 'chunk_' + self.key
37 c = cache.get(cache_key)
39 c = Chunk.objects.get(key=self.key)
40 cache.set(cache_key, c, int(self.cache_time))
42 except Chunk.DoesNotExist:
43 n = Chunk(key=self.key)
48 register.tag('chunk', do_get_chunk)
51 def attachment(key, cache_time=0):
53 cache_key = 'attachment_' + key
54 c = cache.get(cache_key)
56 c = Attachment.objects.get(key=key)
57 cache.set(cache_key, c, int(cache_time))
58 return c.attachment.url
59 except Attachment.DoesNotExist:
62 register.simple_tag(attachment)