Django - open and end a session

Hope someone can help me.

I am trying to execute the "number of users online" counter on the home page of my site. I remember in the good old days of ASP, I had the opportunity to keep a counter going with session.onstart and session.onend.

How to do it in Django?

Greetings

Rich

+3
source share
4 answers

django signals are very convenient:

# 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 will need to delete the reguraly session, as they can remain in the database if the user does not click on "logout", which is most often found. just add this to cron:

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

In addition, I usually add this to my manage.py file for the convenience of setting up .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 IMHO server asset sessions.

+8
source
 from django.contrib.sessions.models import Session import datetime users_online = Session.objects.filter(expire_date__gte = datetime.datetime.now()).count() 

This works, of course, only if you use a database repository for sessions. Anything more esoteric, like memcache, will require your own.

+5
source

Sorry, I do not believe that you could accurately calculate ASP / IIS. The server simply cannot tell the difference between the user leaving the browser open on the site, doing nothing, going to another page or closing the browser completely.

Even if the session cookie expires when the browser is closed, it still doesn’t tell the server anything - the browser is now closed, so what does the server know? This is just an expired client cookie.

The best you can do is evaluate based on the end of the session, as Elf suggested.

+1
source

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

+1
source

All Articles