1 from django import template
2 from django.db import models
3 from django.core.cache import cache
4 from ..models import Chunk, Attachment
7 register = template.Library()
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)
27 class ChunkNode(template.Node):
28 def __init__(self, key, cache_time=0):
30 self.cache_time = cache_time
32 def render(self, context):
34 cache_key = 'chunk_' + self.key
35 c = cache.get(cache_key)
37 c = Chunk.objects.get(key=self.key)
38 cache.set(cache_key, c, int(self.cache_time))
40 except Chunk.DoesNotExist:
41 n = Chunk(key=self.key)
46 register.tag('chunk', do_get_chunk)
49 def attachment(key, cache_time=0):
51 cache_key = 'attachment_' + key
52 c = cache.get(cache_key)
54 c = Attachment.objects.get(key=key)
55 cache.set(cache_key, c, int(cache_time))
56 return c.attachment.url
57 except Attachment.DoesNotExist:
60 register.simple_tag(attachment)