What is the best way to implement the "last seen" feature in a django web application?

I have a working django / apache2 + memcached (ubuntu) application and you want to track the logon of users on the network.

What would be the best way to track this?

I would prefer not to write to the database every time a registered user loads a page; but what other options are there?

+7
python django apache2
source share
4 answers

The approach may be:

you create middleware that does the following in process_response:

  • check a cookie called online, but only if the user is authenticated.
  • If the cookie does not exist,
    • set a cookie called "online" with a value of "1"
    • set the duration of the cookie to 10 minutes.
    • update the "last_login" auth.User field for this user with the current lifetime

Now you have all registered users in your auth.User table. All users who have last_login newer than datetime.now () - interval (15 minutes) can be considered "online".

A database will be recorded for each registered user every 10 minutes. Adjust the values ​​of β€œ10” and β€œ15” to suit your needs.

The advantage is that database entries are rare (according to your two 10/15 digital settings). And to optimize the speed, make sure that last_login is indexed, so the filter in this field, including Count, is really fast.

Hope this helps.

+4
source share

A hashmap or queue in memory with a task running every hour or so to save it.

+1
source share

You need to save the information server part, integrity is not critical, bandwidth and latency are important. This means that you must use some kind of store of key values.

Memcached and redis have expired keys. You may have already installed memcached, so use this.

You can reset the user:last-seen:$username key expiration time every time you visit it, or you can use the mawimawi cookie technique and expiration date = 4 * cookie-life.

+1
source share

You cannot do this in django without using a database / persistent storage for the same reason that django sessions are stored in the database: there may be several instances of your applications, and you need to synchronize their states + data through a single source of persistence [1]

Alternatively, you may need to write this information to a folder in the file with the user ID, and then check its creation / change date to find the necessary information.

0
source share

All Articles