comparison smiley/models.py @ 581:ee87ea74d46b

For Django 1.4, rearranged project structure for new manage.py.
author Brian Neal <bgneal@gmail.com>
date Sat, 05 May 2012 17:10:48 -0500
parents gpp/smiley/models.py@3a626c48e9ae
children 0729c73d5761
comparison
equal deleted inserted replaced
580:c525f3e0b5d0 581:ee87ea74d46b
1 """
2 Models for the smiley application.
3 """
4 import re
5
6 from django.db import models
7 from django.core.cache import cache
8
9 CACHE_TIMEOUT = 60 * 60 # seconds
10
11
12 class SmileyManager(models.Manager):
13
14 def get_smiley_map(self):
15 """
16 Returns a dictionary, the keys are smiley codes.
17 The values are the HTML representations of the keys.
18 The dictionary is cached.
19 """
20 map = cache.get('smiley_map')
21 if map:
22 return map
23
24 map = dict((s.code, s.html()) for s in self.all())
25 cache.set('smiley_map', map, CACHE_TIMEOUT)
26 return map
27
28 def get_smilies(self, extra=False):
29 """
30 Returns smiley model instances filtered by the extra flag.
31 """
32 key = 'smileys' if not extra else 'smileys_extra'
33 smilies = cache.get(key)
34 if smilies:
35 return smilies
36
37 smilies = self.filter(is_extra=extra)
38 cache.set(key, smilies, CACHE_TIMEOUT)
39 return smilies
40
41 def get_smiley_regexes(self):
42 """
43 Returns a list of 2-tuples of the form: (regex, repl)
44 where regex is a regular expression for a smiley and
45 repl is the replacement image in Markdown format.
46 """
47 regexes = cache.get('smiley_regexes')
48 if regexes:
49 return regexes
50
51 regexes = [(re.compile(r"(^|\s|(?<=\s))%s(\s|$)" % re.escape(s.code)),
52 r"\1%s\2" % s.markdown()) for s in self.all()]
53 cache.set('smiley_regexes', regexes, CACHE_TIMEOUT)
54 return regexes
55
56
57 class Smiley(models.Model):
58 image = models.ImageField(upload_to='smiley/images/')
59 title = models.CharField(max_length=32)
60 code = models.CharField(max_length=32)
61 is_extra = models.BooleanField()
62
63 objects = SmileyManager()
64
65 class Meta:
66 verbose_name_plural = 'Smilies'
67 ordering = ('title', )
68
69 def __unicode__(self):
70 return self.title
71
72 def get_absolute_url(self):
73 return self.image.url
74
75 def html(self):
76 """Returns a HTML img tag representation of the smiley."""
77 if self.image:
78 return (u'<img src="%s" alt="%s" title="%s" />' %
79 (self.get_absolute_url(), self.title, self.title))
80 return u''
81 html.allow_tags = True
82
83 def markdown(self):
84 """Returns a markdown representation of the smiley."""
85 if self.image:
86 return (u'![%s](%s "%s")' %
87 (self.title, self.get_absolute_url(), self.title))
88 return u''