1

I have a middleware that checks a session value and redirects depending that value. My problem is, it is creating an infinite redirect loop and I'm not sure why.

So, what I want to do is check to see if the value of the session visible is yes and if not redirect the user to my test view.

Here is my middleware:

class CheckStatus(object):  

    def process_request(self, request):    
        if request.user.is_authenticated():                

                s = request.session.get('visible')
                if str(s) is not 'yes':
                    return HttpResponseRedirect(reverse("myapp.myview.views.test"))
imns
  • 4,996
  • 11
  • 57
  • 80
  • You are lacking the information how the urls for `myapp.myview.views.text` are configured. I suppose it should be "/tests/" - otherwise it could result in an infinite loop... – Bernhard Vallant Aug 31 '10 at 21:38
  • Yeah, myapp.myview.views.text url should be "/test/". So, if the session visible isn't yes, I want to redirect the user to "/test/" – imns Aug 31 '10 at 21:53
  • You should also make sure to populate s with a default if the key is not set: `s = request.session.get('visible', 'no')`. – Bernhard Vallant Aug 31 '10 at 22:09
  • Good call on that @lazerscience. Can any body else offer an advice on how I should do what I am trying to accomplish in my original post? – imns Aug 31 '10 at 22:47
  • You should also consider that the method above will be called for every request, which can also include images, stylesheets etc (when running on the development server), so you probably redirect to another page, that produces additional requests which result in a new redirect? – Bernhard Vallant Aug 31 '10 at 22:48
  • @lazerscience yes, I think that's what's happening now that you have pointed it out. I am testing this locally at the moment. How do I get the middleware to only run once per request? – imns Aug 31 '10 at 23:00

1 Answers1

3

You should at least avoid having it run when serving some media files:

from django.conf import settings

class CheckStatus(object):  

    def process_request(self, request):    
        if request.user.is_authenticated():                
           if not request.path.startswith(settings.MEDIA_URL):
                s = request.session.get('visible')
                if str(s) is not 'yes':
                    return HttpResponseRedirect(reverse("myapp.myview.views.test"))

But the more descent way seems to be using the process_view-method!

Bernhard Vallant
  • 49,468
  • 20
  • 120
  • 148
  • interestingly enough I tried the proccess view thinking the same thing, but it still gets called for every media file that gets loaded. – imns Sep 01 '10 at 00:11
  • on the development server a view gets called for every media request, you need to exclude this in `process_view` as well! – Bernhard Vallant Sep 01 '10 at 08:50