Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the best way to implement a 'last seen' function in a django web app?

I have a running django/apache2 + memcached app (ubuntu) and would like to keep track of logged in users that are online.

What would be the best way to track this?

I would prefer not writing to the database each time a logged in user loads a page; but what other options are there?

like image 786
Hobhouse Avatar asked Jun 12 '10 08:06

Hobhouse


People also ask

Can I make Web app with Django?

The popular Python programming language can be applied using the Django framework to spin up apps.

Can we create app using Python Django?

Use the django-admin tool to generate a project folder, the basic file templates, and manage.py, which serves as your project management script. Use manage.py to create one or more applications.

Is Django a Web server?

Django is an extremely popular and fully featured server-side web framework, written in Python. This module shows you why Django is one of the most popular web server frameworks, how to set up a development environment, and how to start using it to create your own web applications.

What can do with Django?

Django can be (and has been) used to build almost any type of website — from content management systems and wikis, through to social networks and news sites. It can work with any client-side framework, and can deliver content in almost any format (including HTML, RSS feeds, JSON, and XML).


1 Answers

An approach might be:

you create a middleware that does the following on process_response:

  • check for a cookie called 'online', but only if the user is authenticated
  • if the cookie is not there,
    • set a cookie called 'online' with value '1'
    • set the lifespan of the cookie to 10 minutes
    • update the 'last_login' field of auth.User for this user with the current datetime

now you have all currently logged in users in your auth.User table. All Users that have a last_login newer than datetime.now()-interval(15minutes) might be considered "online".

The database will be written for every logged in user about every 10 minutes. Adjust the values "10" and "15" to your needs.

The advantage here is that database writes are rare (according to your two numeric settings 10/15). And for speed optimization make sure that last_login is indexed, so a filter on this field including Count is really fast.

Hope this helps.

like image 99
mawimawi Avatar answered Sep 28 '22 07:09

mawimawi