comparison venv/lib/python2.7/site-packages/requests_toolbelt/auth/guess.py @ 0:d67268158946 draft

planemo upload commit a3f181f5f126803c654b3a66dd4e83a48f7e203b
author bcclaywell
date Mon, 12 Oct 2015 17:43:33 -0400
parents
children
comparison
equal deleted inserted replaced
-1:000000000000 0:d67268158946
1 # -*- coding: utf-8 -*-
2 """The module containing the code for GuessAuth."""
3 from requests import auth
4 from requests import cookies
5
6
7 class GuessAuth(auth.AuthBase):
8 """Guesses the auth type by the WWW-Authentication header."""
9 def __init__(self, username, password):
10 self.username = username
11 self.password = password
12 self.auth = None
13 self.pos = None
14
15 def handle_401(self, r, **kwargs):
16 """Resends a request with auth headers, if needed."""
17
18 www_authenticate = r.headers.get('www-authenticate', '').lower()
19
20 if 'basic' in www_authenticate:
21 if self.pos is not None:
22 r.request.body.seek(self.pos)
23
24 # Consume content and release the original connection
25 # to allow our new request to reuse the same one.
26 r.content
27 r.raw.release_conn()
28 prep = r.request.copy()
29 if not hasattr(prep, '_cookies'):
30 prep._cookies = cookies.RequestsCookieJar()
31 cookies.extract_cookies_to_jar(prep._cookies, r.request, r.raw)
32 prep.prepare_cookies(prep._cookies)
33
34 self.auth = auth.HTTPBasicAuth(self.username, self.password)
35 prep = self.auth(prep)
36 _r = r.connection.send(prep, **kwargs)
37 _r.history.append(r)
38 _r.request = prep
39
40 return _r
41
42 if 'digest' in www_authenticate:
43 self.auth = auth.HTTPDigestAuth(self.username, self.password)
44 # Digest auth would resend the request by itself. We can take a
45 # shortcut here.
46 return self.auth.handle_401(r, **kwargs)
47
48 def __call__(self, request):
49 if self.auth is not None:
50 return self.auth(request)
51
52 try:
53 self.pos = request.body.tell()
54 except AttributeError:
55 pass
56
57 request.register_hook('response', self.handle_401)
58 return request