Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django - detect session start and end

Tags:

django

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

like image 771
Rich Avatar asked Nov 03 '10 01:11

Rich


2 Answers

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.

like image 92
jujule Avatar answered Oct 06 '22 01:10

jujule


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.

like image 34
Elf Sternberg Avatar answered Oct 06 '22 02:10

Elf Sternberg