我正在尝试为网页实现以下方案。如果用户在5秒内处于非活动状态,请注销用户。我有request.session [' islogin'],我想在用户处于非活动状态5秒后将此会话密钥重新分配给False。我曾尝试使用装饰器但是在几个代码之后,我还没弄清楚我应该写下一个什么,以便我的代码将检测非活动用户。因此,我有问题"我如何检测用户是否处于非活动状态5秒钟,以便将会话密钥isLogin分配给False?
答案 0 :(得分:2)
您可以为此制作中间件
<强> middleware.py 强>
from datetime import datetime, timedelta
from django.conf import settings
from django.contrib import auth
class AutoLogout:
def process_request(self, request):
if not request.user.is_authenticated() :
#Can't log out if not logged in
return
try:
if datetime.now() - request.session['last_touch'] > timedelta( 0, settings.AUTO_LOGOUT_DELAY * 60, 0):
auth.logout(request)
del request.session['last_touch']
return
except KeyError:
pass
request.session['last_touch'] = datetime.now()
在您的设置中,将其添加到middleware_classes中:
MIDDLEWARE_CLASSES = [
.................
'app_name.middleware.AutoLogout',
]
and this:
# Auto logout delay in minutes
AUTO_LOGOUT_DELAY = 60 #this is equivalent for 1 hour