开发者

Django: infinite redirects in cookie-setting code?

开发者 https://www.devze.com 2023-02-22 05:14 出处:网络
This cookie-setting/redirecting Django views code is resulting in a redirect loop, even for browsers with cookies enabled. Can anyone explain how to fix it?

This cookie-setting/redirecting Django views code is resulting in a redirect loop, even for browsers with cookies enabled. Can anyone explain how to fix it?

In urls.py:

url(r'^$', 'library.views.ho开发者_C百科me', name="home"),
url(r'^ldap/(?P<next>[\w-]*)/$', 'library.views.update_session_from_ldap', name="ldap"),

In views.py:

def home(request):
    print 'home'
    current_user = request.COOKIES.get('ldap_user', None)
    print current_user
    if not current_user:
        return redirect('/ldap', next='/')
    print 'now here'
# url = '/ldap'
def update_session_from_ldap(request, next):
    remote_user = request.META.get('REMOTE_USER', None)
    hrr = HttpResponseRedirect(next)
    hrr.set_cookie('ldap_user', remote_user)
    print 'set cookie!'
    return hrr

I just see...

home
None
[04/Apr/2011 23:21:17] "GET / HTTP/1.1" 302 0
set cookie!
[04/Apr/2011 23:21:17] "GET / HTTP/1.1" 302 0
set cookie!
[04/Apr/2011 23:21:17] "GET / HTTP/1.1" 302 0
set cookie!... ad infinitum until the browser intervenes

If I reload the page a second time, it is OK: the print statement shows the correct value and there is no redirect, so the cookie is working. It's just the first time the code runs that it goes into an infinite loop.

Any ideas? Any better ways to solve this problem?

The problem is the same in Firefox and Chrome.

Thanks!

UPDATE: I think the problem is in the way that the URLs are configured: I need to work out a way to go from 'home' to 'ldap' and back again, somehow. I think at the moment 'ldap' is just redirecting to itself.


Doesn't look like your regex will match a /:

urls.py:

url(r'^ldap/(?P<next>[\w-]*)/$', 'library.views.update_session_from_ldap', name="ldap"),

views.py:

def update_session_from_ldap(request, next):
    if next is None:
        hrr = HttpResponseRedirect("/")
    else:
        hrr = HttpResponseRedirect(next)
    remote_user = request.META.get('REMOTE_USER', None)
    hrr.set_cookie('ldap_user', remote_user)
    print 'set cookie!'
    return hrr
0

精彩评论

暂无评论...
验证码 换一张
取 消