"""
models.py
"""
from django.db import models
from django.contrib.auth.signals import user_logged_in, user_logged_out
class LoggedUser(models.Model):
username = models.CharField(max_length=30, primary_key=True)
def __unicode__(self):
return self.username
def login_user(sender, request, user, **kwargs):
LoggedUser(username=user.username).save()
def logout_user(sender, request, user, **kwargs):
try:
u = LoggedUser.objects.get(pk=user.username)
u.delete()
except LoggedUser.DoesNotExist:
pass
user_logged_in.connect(login_user)
user_logged_out.connect(logout_user)
"""
This is an example view in views.py that shows all logged users
"""
from django.shortcuts import render_to_response
from django.template import RequestContext
from usuarios.models import LoggedUser
def logged(request):
logged_users = LoggedUser.objects.all().order_by('username')
return render_to_response('users/logged.html',
{'logged_users': logged_users},
context_instance=RequestContext(request))
Comments
Wouldn't it be better to just query the Django sessions? That would be session backend specific though.
I don't think the above code works with multi-process wsgi workers.
#
Maybe it would be safer to store the logged users list in the database.
About sessions, I would like to know more about it. I found some things in this article question: How to lookup django session for a particular user? and the best answer says:
"This is somewhat tricky to do, because not every session is necessarily associated with an authenticated user; Django's session framework supports anonymous sessions as well, and anyone who visits your site will have a session, regardless of whether they're logged in.
This is made trickier still by the fact that the session object itself is serialized -- since Django has no way of knowing which data exactly you want to store, it simply serializes the dictionary of session data into a string (using Python's standard "pickle" module) and stuffs that into your database."
#
I tested the code in production (webfaction/apache2/django1.4.1) and it didn't work very well. Using the developer server everything goes the right way.
I will move the logged users list to the database and test again. If it works ok, I will update the code.
#
I moved the user logged list to the database and now it seems to be working properly. I tested in a WebFaction with Apache server, mod_wsgi 3.4, Python 2.7 installed and running Django 1.4 with an extremely low load.
#