5

I hope someone can help me with this.

I am trying implement a 'number of users online' counter on the home page of my site. I remember in the bad old days of ASP I used to be able to keep a counter going with a session.onstart and session.onend.

How do I do it in Django?

Cheers

Rich

Rich
  • 1,769
  • 3
  • 20
  • 30

4 Answers4

11

django signals are very handy :

# this is in a models.py file
from django.db.models.signals import pre_delete
from django.contrib.sessions.models import Session

def sessionend_handler(sender, **kwargs):
    # cleanup session (temp) data
    print "session %s ended" % kwargs.get('instance').session_key

pre_delete.connect(sessionend_handler, sender=Session)

you'll need to delete your session reguraly as they can stay in the database if the user doesnt click 'logout' which the case most often. just add this to a cron :

*/5 * * * * djangouser /usr/bin/python2.5 /home/project/manage.py cleanup

also i usually add this to my manage.py for easy settings.py path find :

import sys
import os
BASE_DIR = os.path.split(os.path.abspath(__file__))[0]
sys.path.insert(0, BASE_DIR)

SESSION_EXPIRE_AT_BROWSER_CLOSE works but only affects client cookies, not server-actives sessions IMHO.

jujule
  • 11,125
  • 3
  • 42
  • 63
  • When is such signal issued? Please, see https://stackoverflow.com/questions/54170116/do-sessions-in-django-expire-without-a-request – Serge Rogatch Jan 13 '19 at 15:22
6
from django.contrib.sessions.models import Session
import datetime
users_online = Session.objects.filter(expire_date__gte = datetime.datetime.now()).count()

This only works, of course, if you're using database storage for Sessions. Anything more esoteric, like memcache, will require you roll your own.

Elf Sternberg
  • 16,129
  • 6
  • 60
  • 68
  • 1
    Are you sure the sessions get cleaned up when the user closes their browser? In my experience they do not even though I have SESSION_EXPIRE_AT_BROWSER_CLOSE=True – Rich Nov 03 '10 at 02:13
  • I also have a user persistance mechanism that overrides the setting. It doesn't work yet as I can't get the session to delete. Maybe I will kill two birds with one stone here! – Rich Nov 03 '10 at 02:14
  • 2
    No, they don't get cleaned up when the user closes their browser, sadly. But they do expire, and you should be checking for that; hence my filter. How exact do you need this answer to be? You should be running "./manage.py cleanup" every hour, under cron, to clean out old sessions. – Elf Sternberg Nov 03 '10 at 02:31
  • I guess I wanted an accurate count. I could get that on ASP/IIS so it's a shame Django won't let me. Have you ever managed to use SESSION_EXPIRE_AT_BROWSER_CLOSE? – Rich Nov 03 '10 at 06:05
1

Sorry, I don't believe you could get an accurate count on ASP/IIS. It's simply not possible for a server to tell the difference between the user leaving the browser open on a site without doing anything, navigating away to a different page, or closing the browser completely.

Even if the session cookie expires at browser close, that still doesn't tell the server anything - the browser has now closed, so what is going to let the server know? It's simply the client-side cookie that has expired.

The best thing you can do is to estimate based on session expires, as Elf has suggested.

Daniel Roseman
  • 588,541
  • 66
  • 880
  • 895
  • 1
    It was a long time ago that I used ASP but I seem to remember something like a session.onstart and a session.onend event that was is a file something like globals.asp. – Rich Nov 10 '10 at 07:12
  • It was literally 8 years ago since I last used it so I might be wrong, it's irrelevant now anyway was it was ASP not .net! – Rich Nov 10 '10 at 07:12
1

If you need to track the active users you can try http://code.google.com/p/django-tracking/

Ankit Jaiswal
  • 22,859
  • 5
  • 41
  • 64