Rich
Rich

Reputation: 1779

Django - detect session start and end

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

Upvotes: 5

Views: 7660

Answers (4)

jujule
jujule

Reputation: 11531

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.

Upvotes: 11

Ankit Jaiswal
Ankit Jaiswal

Reputation: 23427

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

Upvotes: 1

Daniel Roseman
Daniel Roseman

Reputation: 599580

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.

Upvotes: 1

Elf Sternberg
Elf Sternberg

Reputation: 16361

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.

Upvotes: 6

Related Questions