Django中获取所有在线用户信息
from datetime import timedelta, datetime
from django.core.cache import cache
from django.contrib.sites.models import Site
ONLINE_MINUTES = 10
CACHE_KEY = '%s_online_user_ids' % Site.objects.get_current().domain
_last_purged = datetime.now()
def get_online_user_ids():
user_dict = cache.get(CACHE_KEY)
return hasattr(user_dict, 'keys') and user_dict.keys() or []
class OnlineUsers(object):
def process_request(self, request):
if request.user.is_anonymous():
return
user_dict = cache.get(CACHE_KEY)
if not user_dict:
# initialization
user_dict = {}
now = datetime.now()
user_dict[request.user.id] = now
# purge
global _last_purged
if _last_purged + timedelta(minutes=ONLINE_MINUTES) < now:
purge_older_than = now - timedelta(minutes=ONLINE_MINUTES)
for user_id, last_seen in user_dict.items():
if last_seen < purge_older_than:
del(user_dict[user_id])
_last_purged = now
cache.set(CACHE_KEY, user_dict, 60*60*24)
This stores a dictionary in the form: {user_id: last_seen_time, ...}
in the cache and updates the cache once for every request by an
authenticated user.
An alternative would be to store a structure like Jeremy's,
{minute_seen: set(user_id, ...), ...} which I think will result in
nearly the same amount of cache hits on average.
I would like to hear your comments.
大数据培训、人工智能培训、Python培训、大数据培训机构、大数据培训班、数据分析培训、大数据可视化培训,就选光环大数据!光环大数据,聘请专业的大数据领域知名讲师,确保教学的整体质量与教学水准。讲师团及时掌握时代潮流技术,将前沿技能融入教学中,确保学生所学知识顺应时代所需。通过深入浅出、通俗易懂的教学方式,指导学生更快的掌握技能知识,成就上万个高薪就业学子。 更多问题咨询,欢迎点击------>>>>在线客服!