comparison gpp/forums/stats.py @ 395:e10fa0d8e7ad

Fixing #192; cache some forum stats and have them be computed outside of the request/response cycle. Update the template tag to just read the cache.
author Brian Neal <bgneal@gmail.com>
date Fri, 25 Mar 2011 00:27:10 +0000
parents
children e94570675664
comparison
equal deleted inserted replaced
394:2cb0cc334c50 395:e10fa0d8e7ad
1 """
2 This module is responsible for managing various forum statistics.
3
4 """
5 from django.core.cache import cache
6 from django.contrib.auth.models import User
7
8 from forums.models import Post
9
10
11 CACHE_KEY = 'forums-stats'
12 CACHE_TIMEOUT = 4 * 60 * 60 # seconds
13
14
15 def calc_stats():
16 """
17 This function is responsible for computing the forum statistics.
18 A tuple is returned: (forums post count, active user count, latest username)
19
20 """
21 post_count = Post.objects.all().count()
22 user_count = User.objects.all().count()
23
24 if user_count > 0:
25 latest_user = User.objects.filter(is_active=True).values_list(
26 'username', flat=True).order_by('-date_joined')[0]
27 else:
28 latest_user = None
29
30 return post_count, user_count, latest_user
31
32
33 def update_stats():
34 """
35 This function is responsible for computing the forum statistics and
36 inserting them into the cache. The stats are returned.
37
38 This function should be run periodically, preferably outside of the
39 request/response cycle. On MySQL under InnoDb it is expensive to retrieve
40 the total post count.
41
42 """
43 stats = calc_stats()
44 cache.set(CACHE_KEY, stats, CACHE_TIMEOUT)
45 return stats
46
47
48 def retrieve_stats():
49 """
50 This function retrieves the forum stats from the cache if they are
51 available. If there is a cache-miss, the stats are calcuated, the cache is
52 updated, and the stats returned.
53
54 """
55 stats = cache.get(CACHE_KEY)
56 if stats is None:
57 stats = update_stats()
58
59 return stats