gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 16:29:27 25 4
gpt4 key购买 nike

在模板中,当我使用

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

结果证明,用户始终在线,即使他们已退出一段时间。所以我想知道如何正确检查在线用户?

最佳答案

‌谢谢this优秀的博客文章,稍作修改,我想出了一个更好的解决方案,它使用内存缓存,因此每个请求的延迟更少:

在models.py中添加:

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

并将这些方法添加到 userprofile 类中:
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
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并添加:
    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 中:
 <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>

就是这样!

要在控制台中测试缓存,以确保 memcache 正常工作:
$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 - 如何在django模板中检查用户是否在线?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29663777/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com