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