Mercurial > public > sg101
comparison gpp/forums/middleware.py @ 160:2eb3984ccb15
Implement #45, add a who's online feature for the forums. Created middleware that caches usernames and guest session ids in the cache. Added a tag that displays this info.
author | Brian Neal <bgneal@gmail.com> |
---|---|
date | Tue, 22 Dec 2009 02:08:05 +0000 |
parents | |
children |
comparison
equal
deleted
inserted
replaced
159:416353def4ca | 160:2eb3984ccb15 |
---|---|
1 """ | |
2 Middleware for the forums application. | |
3 """ | |
4 import datetime | |
5 | |
6 from django.core.cache import cache | |
7 from django.conf import settings | |
8 | |
9 | |
10 USER_ONLINE_TIMEOUT = datetime.timedelta(minutes=15) | |
11 USERS_ONLINE_KEY = 'users_online' | |
12 GUESTS_ONLINE_KEY = 'guests_online' | |
13 USERS_CACHE_TIMEOUT = 60 * 60 * 24 # units are seconds | |
14 | |
15 | |
16 class WhosOnline(object): | |
17 """ | |
18 This middleware class keeps track of which registered users have | |
19 been seen recently, and the number of unique unregistered users. | |
20 We use the Django cache system to store this information. | |
21 This middleware should come after the authentication middleware, | |
22 as we count on the user attribute being attached to the request. | |
23 """ | |
24 | |
25 def process_request(self, request): | |
26 """ | |
27 Keep track of who is online. | |
28 """ | |
29 now = datetime.datetime.now() | |
30 cutoff = now - USER_ONLINE_TIMEOUT | |
31 users_online = cache.get(USERS_ONLINE_KEY, {}) | |
32 guests_online = cache.get(GUESTS_ONLINE_KEY, {}) | |
33 | |
34 # update timestamp for user | |
35 if request.user.is_authenticated(): | |
36 users_online[request.user.username] = now | |
37 else: | |
38 sid = request.COOKIES.get(settings.SESSION_COOKIE_NAME, '') | |
39 guests_online[sid] = now | |
40 | |
41 # expire old records | |
42 for username, timestamp in users_online.items(): | |
43 if timestamp < cutoff: | |
44 del users_online[username] | |
45 | |
46 for sid, timestamp in guests_online.items(): | |
47 if timestamp < cutoff: | |
48 del guests_online[sid] | |
49 | |
50 cache.set(USERS_ONLINE_KEY, users_online, USERS_CACHE_TIMEOUT) | |
51 cache.set(GUESTS_ONLINE_KEY, guests_online, USERS_CACHE_TIMEOUT) |