如何检查用户在django模板中是否在线? [英] How to check whether a user is online in django template?

查看:131
本文介绍了如何检查用户在django模板中是否在线?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在模板中,当我使用

  {%如果topic.creator.is_authenticated%} 
在线
{%else%}
离线
{%endif%}

用户即使在一段时间之前已经登出,也始终处于在线状态。所以我想知道如何正确地检查在线用户?

解决方案

谢谢这个优秀的博客文章,稍作修改,我想出了一个更好的解决方案,其中使用memcache,因此每个请求的延迟更少:



在models.py add:

 从django.core.cache导入缓存
导入datetime
从myproject导入设置

并添加这些方法userprofile类:

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

def online(self):
if self.last_seen():
now = datetime.datetime.now ()
如果现在> self.last_seen()+ datetime.timedelta(
seconds = settings.USER_ONLINE_TIMEOUT):
return False
else:
return True
else:
return在userprofile文件夹中添加这个middleware.py




$ / code $ django.core导入缓存
从django.conf导入设置

class ActiveUserMiddleware

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

在settings.py中添加'userprofile.middleware.ActiveUserMiddleware', MIDDLEWARE_CLASSES 添加:

  CACHES = {
'default':{
'BACKEND':'django.core.cache.backends.memcached.MemcachedCache',
'LOCATION':'127.0.0.1:11211',
}
}

#将用户标记为脱机之前不活动的秒数
USER_ONLINE_TIMEOUT = 300

#我们将跟踪的秒数在
#之前的非活动用户#最后一次被从缓存中删除
USER_LASTSEEN_TIMEOUT = 60 * 60 * 24 * 7

和profile.html:

 < table> 
< tr>< th> Last Seen< / th>< td> {%if profile.last_seen%} {{profile.last_seen | timesince}} {%else%} awhile {%endif%}前及LT; / TD>< / TR>
< tr>< th> Online< / th>< td> {{profile.online}}< / td>< / tr>
< / table>

就是这样!



要测试缓存在控制台中,确保memcache工作正常:

  $ memcached -vv 
$ python manage.py shell
>>>从django.core.cache导入缓存
>>> cache.set(foo,bar)
>>>> cache.get(foo)
'bar'
>>> cache.set(foo,zaq)
>>> cache.get(foo)
'zaq'


In template, when I use

{% if topic.creator.is_authenticated %}
Online
{% else %}
Offline
{% endif %}

the users turn out to be always online, even when they has signed out a while ago. So I'm wondering how to check the online users correctly?

解决方案

‌Thanks this excellent blog post, with slight modifications, I came up with a better solution, which uses memcache, hence less delay per request:

in models.py add:

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

and add these method the userprofile class:

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 

in userprofile folder add this 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 settings.py add 'userprofile.middleware.ActiveUserMiddleware', to MIDDLEWARE_CLASSES and also add:

    CACHES = {
        'default': {
            'BACKEND': 'django.core.cache.backends.memcached.MemcachedCache',
            'LOCATION': '127.0.0.1:11211',              
        }
    }

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

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

and in profile.html:

 <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>

That's it!

To test cache in the console, to make sure that memcache works fine:

$memcached -vv
$ python manage.py shell
>>> from django.core.cache import cache
>>> cache.set("foo", "bar")
>>> cache.get("foo")
'bar'
>>> cache.set("foo", "zaq")
>>> cache.get("foo")
'zaq'

这篇关于如何检查用户在django模板中是否在线?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆