f79d495ec2480b11b5063a27a680fd9d79e1489a
[wolnelektury.git] / apps / chunks / templatetags / chunks.py
1 from django import template
2 from django.db import models
3 from django.core.cache import cache
4
5 register = template.Library()
6
7 Chunk = models.get_model('chunks', 'chunk')
8 CACHE_PREFIX = "chunk_"
9
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],)
15     if len(tokens) == 2:
16         tag_name, key = tokens
17         cache_time = 0
18     if len(tokens) == 3:
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)
25
26 class ChunkNode(template.Node):
27     def __init__(self, key, cache_time=0):
28        self.key = key
29        self.cache_time = cache_time
30     
31     def render(self, context):
32         try:
33             cache_key = CACHE_PREFIX + self.key
34             c = cache.get(cache_key)
35             if c is None:
36                 c = Chunk.objects.get(key=self.key)
37                 cache.set(cache_key, c, int(self.cache_time))
38             content = c.content
39         except Chunk.DoesNotExist:
40             n = Chunk(key=self.key)
41             n.save()
42             return ''
43         return content
44         
45 register.tag('chunk', do_get_chunk)