ac762ada656e2d2432aefb24b7d12f44bd9d1eff
[prawokultury.git] / chunks / templatetags / chunks.py
1 from django import template
2 from django.db import models
3 from django.core.cache import cache
4 from ..models import Chunk, Attachment
5
6
7 register = template.Library()
8
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
27 class ChunkNode(template.Node):
28     def __init__(self, key, cache_time=0):
29        self.key = key
30        self.cache_time = cache_time
31
32     def render(self, context):
33         try:
34             cache_key = 'chunk_' + self.key
35             c = cache.get(cache_key)
36             if c is None:
37                 c = Chunk.objects.get(key=self.key)
38                 cache.set(cache_key, c, int(self.cache_time))
39             content = c.content
40         except Chunk.DoesNotExist:
41             n = Chunk(key=self.key)
42             n.save()
43             return ''
44         return content
45
46 register.tag('chunk', do_get_chunk)
47
48
49 def attachment(key, cache_time=0):
50     try:
51         cache_key = 'attachment_' + key
52         c = cache.get(cache_key)
53         if c is None:
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:
58         return ''
59
60 register.simple_tag(attachment)
61