如何在django模板中检查用户是否在线

如何在django模板中检查用户是否在线

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

问题描述

在模板中,当我使用

{% 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 这篇 优秀的博客文章,稍加修改,我想出了一个更好的解决方案,它使用内存缓存,因此每个请求的延迟更少:

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

在models.py中添加:

in models.py add:

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

并将这些方法添加到 userprofile 类中:

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

在 userprofile 文件夹中添加这个 middleware.py

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)

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

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

在 profile.html 中:

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>

就是这样!

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

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模板中检查用户是否在线?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-28 04:40