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
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With