cc25df728782075d49a3121a540f9cbc39411f64
[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
6 register = template.Library()
7
8 Chunk = models.get_model('chunks', 'chunk')
9 Attachment = models.get_model('chunks', 'attachment')
10
11
12 @register.simple_tag
13 def chunk(key, cache_time=0):
14     try:
15         cache_key = Chunk.cache_key(key)
16         c = cache.get(cache_key)
17         if c is None:
18             c = Chunk.objects.get(key=key)
19             cache.set(cache_key, c, int(cache_time))
20         content = c.content
21     except Chunk.DoesNotExist:
22         n = Chunk(key=key)
23         n.save()
24         return ''
25     return content
26
27
28 @register.simple_tag
29 def attachment(key, cache_time=0):
30     try:
31         cache_key = 'attachment_' + key
32         c = cache.get(cache_key)
33         if c is None:
34             c = Attachment.objects.get(key=key)
35             cache.set(cache_key, c, int(cache_time))
36         return c.attachment.url
37     except Attachment.DoesNotExist:
38         return ''