On 1/23/07, Will McCutchen <[EMAIL PROTECTED]> wrote:
...
> I would add option #5:  Write a custom middleware component to update a
> last_accessed attribute for logged in users on every request.
>
> http://www.djangobook.com/en/beta/chapter16/

If you have a lot of requests, I doubt you really want to update a
table on every request.  Hitting the DB is somewhat expensive;
re-pickling a session on top of that is pretty pricey.

The attached file implements a (lightly-tested) middleware.  It makes
a dictionary keyed by datetime down to an even minute.  The value is a
Set of user_id's seen that minute.  This dict is updated by  a request
middleware.  The dict has keys for ONLINE_MINUTES (the number of
minutes you consider a user to be "online") + 1 minutes.  Every
ONLINE_MINUTES * PURGE_MULTIPLE   minutes, it removes old minute keys
from the dictionary.

This allows fast updating no matter how many users you have, fast
counting, and fast eviction.  A downside is that it Includes partial
minutes (i.e. 2 minutes would count up to users seen in 2:59, due to
minute rollover); I think this amount of slop is probably OK given the
reduction in maintenance cost.  ;-)

You'll want to use OnlineUsers.get_online_user_ids() wherever you need
the list of IDs.

If you have multiple web servers, this problem gets more complicated
-- then you probably need to use the DB or some shared process.

Please test it out and tell me if it works.  If you need to -list-
users rather than count them, you may wish to keep usernames or user
objects rather than user_id's.  That's a pretty straight-forward
change if you want it.

Let me know if it's useful; I can post it somewhere for others...

--~--~---------~--~----~------------~-------~--~----~
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to [email protected]
To unsubscribe from this group, send email to [EMAIL PROTECTED]
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en
-~----------~----~----~----~------~----~------~--~---

Attachment: OnlineUsers.py
Description: Binary data

Reply via email to