Posted By

vas3k on 10/21/09


Tagged

python user django


Versions (?)

Who likes this?

2 people have marked this snippet as a favorite

vkolev
sapphiriq


Users Online on Django


 / Published in: Django
 

  1. ### models.py
  2. class UsersOnline(models.Model):
  3. username = models.CharField(max_length=100)
  4. time = models.DateTimeField()
  5. url = models.URLField()
  6.  
  7. def __unicode__(self):
  8. return self.username
  9.  
  10. def recountUsersOnline():
  11. users = UsersOnline.objects.all()
  12. date_now = datetime.now()
  13. # Deleting expired users
  14. for user in users:
  15. dt = date_now - user.time
  16. if (dt.seconds > 300):
  17. # User expired
  18. user.delete()
  19.  
  20. def addUserOnline(username, url):
  21. try:
  22. user = UsersOnline.objects.get(username=username)
  23. user.time = datetime.now()
  24. except:
  25. user = UsersOnline(username=username, time=datetime.now(), url=url)
  26. user.save()

Report this snippet  

Comments

RSS Icon Subscribe to comments
Posted By: SleepWalker on July 23, 2012

I think, that this will be better, when in method recountUsersOnline is better to use .filter() instead of .all():

from datetime import datetime, timedelta

def recountUsersOnline(): date_now = datetime.now() delta = datetime.timedelta(seconds=-300) users = UsersOnline.objects.filter(time__lt=date_now+delta) # Deleting expired users for user in users: user.delete()

You need to login to post a comment.