bgneal@395: """
bgneal@395: This module is responsible for managing various forum statistics.
bgneal@395: 
bgneal@395: """
bgneal@395: from django.core.cache import cache
bgneal@395: from django.contrib.auth.models import User
bgneal@395: 
bgneal@395: from forums.models import Post
bgneal@395: 
bgneal@395: 
bgneal@395: CACHE_KEY = 'forums-stats'
bgneal@395: CACHE_TIMEOUT = 4 * 60 * 60         # seconds
bgneal@395: 
bgneal@395: 
bgneal@395: def calc_stats():
bgneal@395:     """
bgneal@395:     This function is responsible for computing the forum statistics.
bgneal@395:     A tuple is returned: (forums post count, active user count, latest username)
bgneal@395: 
bgneal@395:     """
bgneal@395:     post_count = Post.objects.all().count()
bgneal@395:     user_count = User.objects.all().count()
bgneal@395: 
bgneal@395:     if user_count > 0:
bgneal@395:         latest_user = User.objects.filter(is_active=True).values_list(
bgneal@395:                 'username', flat=True).order_by('-date_joined')[0]
bgneal@395:     else:
bgneal@395:         latest_user = None
bgneal@395: 
bgneal@395:     return post_count, user_count, latest_user
bgneal@395: 
bgneal@395: 
bgneal@395: def update_stats():
bgneal@395:     """
bgneal@395:     This function is responsible for computing the forum statistics and
bgneal@395:     inserting them into the cache. The stats are returned.
bgneal@395: 
bgneal@395:     This function should be run periodically, preferably outside of the
bgneal@395:     request/response cycle. On MySQL under InnoDb it is expensive to retrieve
bgneal@395:     the total post count.
bgneal@395: 
bgneal@395:     """
bgneal@395:     stats = calc_stats()
bgneal@395:     cache.set(CACHE_KEY, stats, CACHE_TIMEOUT)
bgneal@395:     return stats
bgneal@395: 
bgneal@395: 
bgneal@395: def retrieve_stats():
bgneal@395:     """
bgneal@395:     This function retrieves the forum stats from the cache if they are
bgneal@395:     available. If there is a cache-miss, the stats are calcuated, the cache is
bgneal@395:     updated, and the stats returned.
bgneal@395: 
bgneal@395:     """
bgneal@395:     stats = cache.get(CACHE_KEY)
bgneal@395:     if stats is None:
bgneal@395:         stats = update_stats()
bgneal@395: 
bgneal@395:     return stats