django online user

Django: Using Caching to Track Online Users

Recently I wanted a simple solution to track whether a user isonline on a given Django site.  The definition of "online" on asite is kind of ambiguous, so I'll define that a user is considered to beonline if they have made any request to the site in the last fiveminutes. 

 

I found that one approach is to use Django's caching framework totrack when a user last accessed the site.  For example, upon each request,I can have a middleware set the current time as a cache value associated with agiven user.  This allows us to store some basic information aboutlogged-in user's online state without having to hit the database on eachrequest and easily retrieve it by accessing the cache.

 

My approach below.  Comments welcome.

 

In settings.py:

# add the middleware that you areabout to create to settings
MIDDLEWARE_CLASSES =(
    ....
   
'middleware.activeuser_middleware.ActiveUserMiddleware',
    ....
)

# Setup caching per Django docs. Inactuality, you'd probably use memcached instead of local memory.
CACHES = {
   
'default':{
       
'BACKEND':'django.core.cache.backends.locmem.LocMemCache',
       
'LOCATION':'default-cache'
    }
}

# Number of seconds of inactivitybefore a user is marked offline
USER_ONLINE_TIMEOUT = 300

# Number of seconds that we will keeptrack of inactive users for before
# their last seen is removed from the cache
USER_LASTSEEN_TIMEOUT = 60* 60 * 24 * 7

In activeuser_middleware.py:

import datetime
from django.core.cache import cache
from django.conf import settings

class ActiveUserMiddleware:

def process_request(self,request):
        current_user =request.user
       
if request.user.is_authenticated():
            now =datetime.datetime.now()
            cache.
set('seen_%s' % (current_user.username), now,
                          settings.USER_LASTSEEN_TIMEOUT)

In your UserProfile module or someother model associated with the user:

class UserProfile(models.Model):
    ....
    ....

def last_seen(self):
       
return cache.get('seen_%s' %self.user.username)

def online(self):
       
if self.last_seen():
            now =datetime.datetime.now()
           
if now > self.last_seen() +datetime.timedelta(
                        seconds=settings.USER_ONLINE_TIMEOUT):
               
return False
           
else:
               
return True
       
else:
           
return False

Then in the template where you want to display whetherthe user is online or not: 

{% with request.user.get_profile as profile %}

<table>
  
<tr><th>Last Seen</th><td>{% if profile.last_seen %}{{profile.last_seen|timesince }}{% else %}awhile{% endif %} ago</td></tr>
  
<tr><th>Online</th><td>{{ profile.online }}</td></tr>
 
</table>

{% endwith %}

Pros:

 -Simple solution

 -Doesn't need to hit the database for saving the timestamp each request

 

Cons:

  -Last user access times are cleared if the server is rebooted or cache is reset

  -Last user access times are accessible only as long as they exist inthe cache.

 

来自 <http://www.djangocurrent.com/2011/07/django-using-cashing-to-track-online.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值