Merge branch 'auth-digest-multi-thread' of https://github.com/exvito/requests into proposed/2.8.0
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by Ian Cordasco · committed by Ian Cordasco · parents 1e640c8, 5a69137 · Browse files · 2 files·+58 added−27 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
2 files+58 added−27 removed
- other:+58 added−27 removed
Provenance
- Commit
77d7e53- Tree
408bc47- Author
Ian Cordasco <graffatcolmingov@gmail.com>- Committer
Ian Cordasco <graffatcolmingov@gmail.com>- Parent 1
1e640c8- Parent 2
5a69137
2 files changed+58 added−27 removed
modified:requests/auth.py+38 added-27 removed
9 unmodified lines10 import os11 import re12 import time13 import hashlib14+import threading15 16 from base64 import b64encode17 18 from .compat import urlparse, str44 unmodified lines63 """Attaches HTTP Digest Authentication to the given Request object."""64 def __init__(self, username, password):65 self.username = username66 self.password = password66- self.last_nonce = ''67- self.nonce_count = 068- self.chal = {}69- self.pos = None70- self.num_401_calls = 167+ # Keep state in per-thread local storage68+ self._thread_local = threading.local()69 70+ def init_per_thread_state(self):71+ # Ensure state is initialized just once per-thread72+ if not hasattr(self._thread_local, 'init'):73+ self._thread_local.init = True74+ self._thread_local.last_nonce = ''75+ self._thread_local.nonce_count = 076+ self._thread_local.chal = {}77+ self._thread_local.pos = None78+ self._thread_local.num_401_calls = None79+80 def build_digest_header(self, method, url):81 74- realm = self.chal['realm']75- nonce = self.chal['nonce']76- qop = self.chal.get('qop')77- algorithm = self.chal.get('algorithm')78- opaque = self.chal.get('opaque')82+ realm = self._thread_local.chal['realm']83+ nonce = self._thread_local.chal['nonce']84+ qop = self._thread_local.chal.get('qop')85+ algorithm = self._thread_local.chal.get('algorithm')86+ opaque = self._thread_local.chal.get('opaque')87 88 if algorithm is None:89 _algorithm = 'MD5'90 else:30 unmodified lines121 122 HA1 = hash_utf8(A1)123 HA2 = hash_utf8(A2)124 117- if nonce == self.last_nonce:118- self.nonce_count += 1125+ if nonce == self._thread_local.last_nonce:126+ self._thread_local.nonce_count += 1127 else:120- self.nonce_count = 1121- ncvalue = '%08x' % self.nonce_count122- s = str(self.nonce_count).encode('utf-8')128+ self._thread_local.nonce_count = 1129+ ncvalue = '%08x' % self._thread_local.nonce_count130+ s = str(self._thread_local.nonce_count).encode('utf-8')131 s += nonce.encode('utf-8')132 s += time.ctime().encode('utf-8')133 s += os.urandom(8)134 11 unmodified lines146 else:147 # XXX handle auth-int.148 return None149 142- self.last_nonce = nonce150+ self._thread_local.last_nonce = nonce151 152 # XXX should the partial digests be encoded too?153 base = 'username="%s", realm="%s", nonce="%s", uri="%s", ' \154 'response="%s"' % (self.username, realm, nonce, path, respdig)10 unmodified lines165 166 def handle_redirect(self, r, **kwargs):167 """Reset num_401_calls counter on redirects."""168 if r.is_redirect:161- self.num_401_calls = 1169+ self._thread_local.num_401_calls = 1170 171 def handle_401(self, r, **kwargs):172 """Takes the given response and tries digest-auth, if needed."""173 166- if self.pos is not None:174+ if self._thread_local.pos is not None:175 # Rewind the file position indicator of the body to where176 # it was to resend the request.169- r.request.body.seek(self.pos)170- num_401_calls = getattr(self, 'num_401_calls', 1)177+ r.request.body.seek(self._thread_local.pos)178 s_auth = r.headers.get('www-authenticate', '')179 173- if 'digest' in s_auth.lower() and num_401_calls < 2:180+ if 'digest' in s_auth.lower() and self._thread_local.num_401_calls < 2:181 175- self.num_401_calls += 1182+ self._thread_local.num_401_calls += 1183 pat = re.compile(r'digest ', flags=re.IGNORECASE)177- self.chal = parse_dict_header(pat.sub('', s_auth, count=1))184+ self._thread_local.chal = parse_dict_header(pat.sub('', s_auth, count=1))185 186 # Consume content and release the original connection187 # to allow our new request to reuse the same one.188 r.content9 unmodified lines198 _r.request = prep199 200 return _r201 195- self.num_401_calls = 1202+ self._thread_local.num_401_calls = 1203 return r204 205 def __call__(self, r):206+ # Initialize per-thread state, if needed207+ self.init_per_thread_state()208 # If we have a saved nonce, skip the 401200- if self.last_nonce:209+ if self._thread_local.last_nonce:210 r.headers['Authorization'] = self.build_digest_header(r.method, r.url)211 try:203- self.pos = r.body.tell()212+ self._thread_local.pos = r.body.tell()213 except AttributeError:214 # In the case of HTTPDigestAuth being reused and the body of215 # the previous request was a file-like object, pos has the216 # file position of the previous body. Ensure it's set to217 # None.209- self.pos = None218+ self._thread_local.pos = None219 r.register_hook('response', self.handle_401)220 r.register_hook('response', self.handle_redirect)221+ self._thread_local.num_401_calls = 1222+223 return rmodified:test_requests.py+20 added
31 unmodified lines32 import StringIO33 except ImportError:34 import io as StringIO35 36+try:37+ from multiprocessing.pool import ThreadPool38+except ImportError:39+ ThreadPool = None40+41 if is_py3:42 def u(s):43 return s44 else:371 unmodified lines416 417 r = requests.get(url, auth=auth)418 assert '"auth"' in r.request.headers['Authorization']419 420+ def test_DIGESTAUTH_THREADED(self):421+422+ auth = HTTPDigestAuth('user', 'pass')423+ url = httpbin('digest-auth', 'auth', 'user', 'pass')424+ session = requests.Session()425+ session.auth=auth426+427+ def do_request(i):428+ r = session.get(url)429+ assert '"auth"' in r.request.headers['Authorization']430+ return 1431+ if ThreadPool is not None:432+ pool = ThreadPool(processes=50)433+ pool.map(do_request, range(100))434+435 def test_POSTBIN_GET_POST_FILES(self):436 437 url = httpbin('post')438 post1 = requests.post(url).raise_for_status()1258 unmodified lines