Clean up, support all redirects, fix potential endless 401 loop.
authorYossi Gottlieb <yossigo@gmail.com>
Tue, 7 Oct 2014 21:06:01 +0000 (00:06 +0300)
committerYossi Gottlieb <yossigo@gmail.com>
Tue, 7 Oct 2014 21:06:01 +0000 (00:06 +0300)
requests/auth.py

index 41be982995cd672b62ff64430fc80914b1e0e04e..b2b341f5cb913d7be466e30e14a3b594b47654a4 100644 (file)
@@ -17,6 +17,7 @@ from base64 import b64encode
 from .compat import urlparse, str
 from .cookies import extract_cookies_to_jar
 from .utils import parse_dict_header, to_native_string
+from .status_codes import codes
 
 CONTENT_TYPE_FORM_URLENCODED = 'application/x-www-form-urlencoded'
 CONTENT_TYPE_MULTI_PART = 'multipart/form-data'
@@ -150,13 +151,12 @@ class HTTPDigestAuth(AuthBase):
 
         return 'Digest %s' % (base)
 
-    def handle_302(self, r, **kwargs):
+    def handle_redirect(self, r, **kwargs):
         """Reset num_401_calls counter on redirects."""
-        try:
-            delattr(self, 'num_401_calls')
-        except AttributeError:
-            pass
-        return r
+        if r.status_code in (
+                codes.temporary_redirect,
+                codes.permanent_redirect):
+            setattr(self, 'num_401_calls', 1)
 
     def handle_401(self, r, **kwargs):
         """Takes the given response and tries digest-auth, if needed."""
@@ -190,7 +190,7 @@ class HTTPDigestAuth(AuthBase):
 
             return _r
 
-        setattr(self, 'num_401_calls', 1)
+        setattr(self, 'num_401_calls', num_401_calls + 1)
         return r
 
     def __call__(self, r):
@@ -202,5 +202,5 @@ class HTTPDigestAuth(AuthBase):
         except AttributeError:
             pass
         r.register_hook('response', self.handle_401)
-        r.register_hook('response', self.handle_302)
+        r.register_hook('response', self.handle_redirect)
         return r