annotate gpp/forums/middleware.py @ 190:0e4961833cdf

Added some select_related's to downloads.
author Brian Neal <bgneal@gmail.com>
date Thu, 01 Apr 2010 01:57:01 +0000
parents 2eb3984ccb15
children
rev   line source
bgneal@160 1 """
bgneal@160 2 Middleware for the forums application.
bgneal@160 3 """
bgneal@160 4 import datetime
bgneal@160 5
bgneal@160 6 from django.core.cache import cache
bgneal@160 7 from django.conf import settings
bgneal@160 8
bgneal@160 9
bgneal@160 10 USER_ONLINE_TIMEOUT = datetime.timedelta(minutes=15)
bgneal@160 11 USERS_ONLINE_KEY = 'users_online'
bgneal@160 12 GUESTS_ONLINE_KEY = 'guests_online'
bgneal@160 13 USERS_CACHE_TIMEOUT = 60 * 60 * 24 # units are seconds
bgneal@160 14
bgneal@160 15
bgneal@160 16 class WhosOnline(object):
bgneal@160 17 """
bgneal@160 18 This middleware class keeps track of which registered users have
bgneal@160 19 been seen recently, and the number of unique unregistered users.
bgneal@160 20 We use the Django cache system to store this information.
bgneal@160 21 This middleware should come after the authentication middleware,
bgneal@160 22 as we count on the user attribute being attached to the request.
bgneal@160 23 """
bgneal@160 24
bgneal@160 25 def process_request(self, request):
bgneal@160 26 """
bgneal@160 27 Keep track of who is online.
bgneal@160 28 """
bgneal@160 29 now = datetime.datetime.now()
bgneal@160 30 cutoff = now - USER_ONLINE_TIMEOUT
bgneal@160 31 users_online = cache.get(USERS_ONLINE_KEY, {})
bgneal@160 32 guests_online = cache.get(GUESTS_ONLINE_KEY, {})
bgneal@160 33
bgneal@160 34 # update timestamp for user
bgneal@160 35 if request.user.is_authenticated():
bgneal@160 36 users_online[request.user.username] = now
bgneal@160 37 else:
bgneal@160 38 sid = request.COOKIES.get(settings.SESSION_COOKIE_NAME, '')
bgneal@160 39 guests_online[sid] = now
bgneal@160 40
bgneal@160 41 # expire old records
bgneal@160 42 for username, timestamp in users_online.items():
bgneal@160 43 if timestamp < cutoff:
bgneal@160 44 del users_online[username]
bgneal@160 45
bgneal@160 46 for sid, timestamp in guests_online.items():
bgneal@160 47 if timestamp < cutoff:
bgneal@160 48 del guests_online[sid]
bgneal@160 49
bgneal@160 50 cache.set(USERS_ONLINE_KEY, users_online, USERS_CACHE_TIMEOUT)
bgneal@160 51 cache.set(GUESTS_ONLINE_KEY, guests_online, USERS_CACHE_TIMEOUT)