middleware is not work expected

匿名 (未验证) 提交于 2019-12-03 08:33:39

问题:

I have some problem related to that I am trying to implement a middleware which detects the whether the authenticated user is inactive for 5 seconds. I have wrote below Python module to do this job but It seems it is not works well. I found two reason ; One of them is ; I can not redirect the user to the home page correctly ; Middleware is not change session key correctly

I have not found that how I can solve this problems. I will show what I have done to the below as two part.

First part ; middleware.py

class TimeOut:     @csrf_exempt      def process_request(self, request):         try :             if request.session['isA'] == False:                 return #redirect(reverse("homePage_view"))         except KeyError:             request.session['isA'] = False             return         try :             passT = datetime.now() - request.session['Time']              if passT > timedelta( 0, settings.SESSION_COOKIE, 0):                 request.session['isA'] = False                 del request.session['Time']                 return         except KeyError:             pass         request.session['Time'] = datetime.now() 

Second part ; settings.py

SESSION_COOKIE = 5   MIDDLEWARE_CLASSES = (     'home.middleware.TimeOut', ) 

EDIT: I have mistakenly wrote other class. I have changed the name as TimeOut

回答1:

Is this the one you are talking:

class AutoLogout:     def process_request(self, request):         if not request.user.is_authenticated() :             return HttpResponseRedirect(reverse('app_name:url_name'))          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 HttpResponseRedirect(reverse('app_name:url_name'))         except KeyError:             pass          request.session['last_touch'] = datetime.now() 

decorators.py

from django.core.urlresolvers import reverse from django.http import HttpResponseRedirect  def login_check(view_func):     def _wrapped_view_func(request, *args, **kwargs):         if not request.user.is_authenticated:             //return to home page url             return HttpResponseRedirect(reverse('app_name:url_name'))         return view_func(request, *args, **kwargs)     return _wrapped_view_func 

After you create decorators.py, update your view like this:

from app_name.decorators import login_check  @login_check def view_name(request):     ......... 

The user will not be allow to go to that page if not authenticated.



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!