Skip to content
Myr

Update urllib3 to 29aa09bde9c42cc9a8d79aac47ee3d362b438cca

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 · parent 0b6d2e4 · Browse files · 6 files+194 added−80 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

6 files+194 added−80 removed

  • other:+194 added−80 removed

6 files+194 added−80 removed

modified:requests/packages/urllib3/util/connection.py+1 added
80 unmodified lines
81 except socket.error as _:82 err = _83 if sock is not None:84 sock.close()85 sock = None8687 if err is not None:88 raise err89 else:
9 unmodified lines
modified:requests/packages/urllib3/util/ssl_.py+2 added-2 removed
27 unmodified lines
28 from ssl import _DEFAULT_CIPHERS29except ImportError:30 _DEFAULT_CIPHERS = (31 'ECDH+AESGCM:DH+AESGCM:ECDH+AES256:DH+AES256:ECDH+AES128:DH+AES:ECDH+HIGH:'32 'DH+HIGH:ECDH+3DES:DH+3DES:RSA+AESGCM:RSA+AES:RSA+HIGH:RSA+3DES:ECDH+RC4:'33 'DH+RC4:RSA+RC4:!aNULL:!eNULL:!MD5'32 'DH+HIGH:ECDH+3DES:DH+3DES:RSA+AESGCM:RSA+AES:RSA+HIGH:RSA+3DES:!aNULL:'33 '!eNULL:!MD5'34 )3536try:37 from ssl import SSLContext # Modern SSL?
220 unmodified lines
modified:requests/packages/urllib3/_collections.py+167 added-54 removed
12 unmodified lines
13try: # Python 2.7+14 from collections import OrderedDict15except ImportError:16 from .packages.ordered_dict import OrderedDict17from .packages.six import iterkeys, itervalues17from .packages.six import iterkeys, itervalues, PY3181920__all__ = ['RecentlyUsedContainer', 'HTTPHeaderDict']212223MULTIPLE_HEADERS_ALLOWED = frozenset(['cookie', 'set-cookie', 'set-cookie2'])2425_Null = object()262728class RecentlyUsedContainer(MutableMapping):
69 unmodified lines
98 with self.lock:99 return list(iterkeys(self._container))100101102_dict_setitem = dict.__setitem__103_dict_getitem = dict.__getitem__104_dict_delitem = dict.__delitem__105_dict_contains = dict.__contains__106_dict_setdefault = dict.setdefault107108100class HTTPHeaderDict(MutableMapping):109class HTTPHeaderDict(dict):110 """111 :param headers:112 An iterable of field-value pairs. Must not contain multiple field names113 when compared case-insensitively.
23 unmodified lines
137 >>> headers['SET-cookie']138 'foo=bar, baz=quxx'139 >>> headers['Content-Length']140 '7'132133 If you want to access the raw headers with their original casing134 for debugging purposes you can access the private ``._data`` attribute135 which is a normal python ``dict`` that maps the case-insensitive key to a136 list of tuples stored as (case-sensitive-original-name, value). Using the137 structure from above as our example:138139 >>> headers._data140 {'set-cookie': [('Set-Cookie', 'foo=bar'), ('set-cookie', 'baz=quxx')],141 'content-length': [('content-length', '7')]}141 """142143 def __init__(self, headers=None, **kwargs):145 self._data = {}146 if headers is None:147 headers = {}148 self.update(headers, **kwargs)144 dict.__init__(self)145 if headers is not None:146 self.extend(headers)147 if kwargs:148 self.extend(kwargs)149150 def __setitem__(self, key, val):151 return _dict_setitem(self, key.lower(), (key, val))152153 def __getitem__(self, key):154 val = _dict_getitem(self, key.lower())155 return ', '.join(val[1:])156157 def __delitem__(self, key):158 return _dict_delitem(self, key.lower())159160 def __contains__(self, key):161 return _dict_contains(self, key.lower())162163 def __eq__(self, other):164 if not isinstance(other, Mapping) and not hasattr(other, 'keys'):165 return False166 if not isinstance(other, type(self)):167 other = type(self)(other)168 return dict((k1, self[k1]) for k1 in self) == dict((k2, other[k2]) for k2 in other)169170 def __ne__(self, other):171 return not self.__eq__(other)172173 values = MutableMapping.values174 get = MutableMapping.get175 update = MutableMapping.update176 177 if not PY3: # Python 2178 iterkeys = MutableMapping.iterkeys179 itervalues = MutableMapping.itervalues180181 __marker = object()182183 def pop(self, key, default=__marker):184 '''D.pop(k[,d]) -> v, remove specified key and return the corresponding value.185 If key is not found, d is returned if given, otherwise KeyError is raised.186 '''187 # Using the MutableMapping function directly fails due to the private marker.188 # Using ordinary dict.pop would expose the internal structures.189 # So let's reinvent the wheel.190 try:191 value = self[key]192 except KeyError:193 if default is self.__marker:194 raise195 return default196 else:197 del self[key]198 return value199200 def discard(self, key):201 try:202 del self[key]203 except KeyError:204 pass205150 def add(self, key, value):206 def add(self, key, val):207 """Adds a (name, value) pair, doesn't overwrite the value if it already208 exists.209210 >>> headers = HTTPHeaderDict(foo='bar')211 >>> headers.add('Foo', 'baz')212 >>> headers['foo']213 'bar, baz'214 """159 self._data.setdefault(key.lower(), []).append((key, value))215 key_lower = key.lower()216 new_vals = key, val217 # Keep the common case aka no item present as fast as possible218 vals = _dict_setdefault(self, key_lower, new_vals)219 if new_vals is not vals:220 # new_vals was not inserted, as there was a previous one221 if isinstance(vals, list):222 # If already several items got inserted, we have a list223 vals.append(val)224 else:225 # vals should be a tuple then, i.e. only one item so far226 if key_lower in MULTIPLE_HEADERS_ALLOWED:227 # Need to convert the tuple to list for further extension228 _dict_setitem(self, key_lower, [vals[0], vals[1], val])229 else:230 _dict_setitem(self, key_lower, new_vals)231232 def extend(*args, **kwargs):233 """Generic import function for any type of header-like object.234 Adapted version of MutableMapping.update in order to insert items235 with self.add instead of self.__setitem__236 """237 if len(args) > 2:238 raise TypeError("update() takes at most 2 positional "239 "arguments ({} given)".format(len(args)))240 elif not args:241 raise TypeError("update() takes at least 1 argument (0 given)")242 self = args[0]243 other = args[1] if len(args) >= 2 else ()244 245 if isinstance(other, Mapping):246 for key in other:247 self.add(key, other[key])248 elif hasattr(other, "keys"):249 for key in other.keys():250 self.add(key, other[key])251 else:252 for key, value in other:253 self.add(key, value)254255 for key, value in kwargs.items():256 self.add(key, value)257258 def getlist(self, key):259 """Returns a list of all the values for the named field. Returns an260 empty list if the key doesn't exist."""164 return [v for k, v in self._data.get(key.lower(), [])]261 try:262 vals = _dict_getitem(self, key.lower())263 except KeyError:264 return []265 else:266 if isinstance(vals, tuple):267 return [vals[1]]268 else:269 return vals[1:]270166 def copy(self):167 h = HTTPHeaderDict()168 for key in self._data:169 for rawkey, value in self._data[key]:170 h.add(rawkey, value)171 return h271 # Backwards compatibility for httplib272 getheaders = getlist273 getallmatchingheaders = getlist274 iget = getlist275173 def __eq__(self, other):174 if not isinstance(other, Mapping):175 return False176 other = HTTPHeaderDict(other)177 return dict((k1, self[k1]) for k1 in self._data) == \178 dict((k2, other[k2]) for k2 in other._data)276 def __repr__(self):277 return "%s(%s)" % (type(self).__name__, dict(self.itermerged()))278180 def __getitem__(self, key):181 values = self._data[key.lower()]182 return ', '.join(value[1] for value in values)279 def copy(self):280 clone = type(self)()281 for key in self:282 val = _dict_getitem(self, key)283 if isinstance(val, list):284 # Don't need to convert tuples285 val = list(val)286 _dict_setitem(clone, key, val)287 return clone288184 def __setitem__(self, key, value):185 self._data[key.lower()] = [(key, value)]289 def iteritems(self):290 """Iterate over all header lines, including duplicate ones."""291 for key in self:292 vals = _dict_getitem(self, key)293 for val in vals[1:]:294 yield vals[0], val295187 def __delitem__(self, key):188 del self._data[key.lower()]296 def itermerged(self):297 """Iterate over all headers, merging duplicate ones together."""298 for key in self:299 val = _dict_getitem(self, key)300 yield val[0], ', '.join(val[1:])301190 def __len__(self):191 return len(self._data)302 def items(self):303 return list(self.iteritems())304193 def __iter__(self):194 for headers in itervalues(self._data):195 yield headers[0][0]196197 def __repr__(self):198 return '%s(%r)' % (self.__class__.__name__, dict(self.items()))199200 def update(self, *args, **kwds):201 headers = args[0]202 if isinstance(headers, HTTPHeaderDict):203 for key in iterkeys(headers._data):204 self._data.setdefault(key.lower(), []).extend(headers._data[key])205 else:206 super(HTTPHeaderDict, self).update(*args, **kwds)305 @classmethod306 def from_httplib(cls, message, duplicates=('set-cookie',)): # Python 2307 """Read headers from a Python 2 httplib message object."""308 ret = cls(message.items())309 # ret now contains only the last header line for each duplicate.310 # Importing with all duplicates would be nice, but this would311 # mean to repeat most of the raw parsing already done, when the312 # message object was created. Extracting only the headers of interest 313 # separately, the cookies, should be faster and requires less314 # extra code.315 for key in duplicates:316 ret.discard(key)317 for val in message.getheaders(key):318 ret.add(key, val)319 return ret
modified:requests/packages/urllib3/connectionpool.py+2 added-3 removed
586 unmodified lines
587 # be replaced during the next _get_conn() call.588 conn.close()589 conn = None590591 stacktrace = sys.exc_info()[2]591 if isinstance(e, SocketError) and self.proxy:592 e = ProxyError('Cannot connect to proxy.', e)593 elif isinstance(e, (SocketError, HTTPException)):594 e = ProtocolError('Connection aborted.', e)595597 retries = retries.increment(method, url, error=e,598 _pool=self, _stacktrace=stacktrace)596 retries = retries.increment(method, url, error=e, _pool=self,597 _stacktrace=sys.exc_info()[2])598 retries.sleep()599600 # Keep track of the error for the retry warning.601 err = e
195 unmodified lines
modified:requests/packages/urllib3/poolmanager.py+9 added-2 removed
6 unmodified lines
78from ._collections import RecentlyUsedContainer9from .connectionpool import HTTPConnectionPool, HTTPSConnectionPool10from .connectionpool import port_by_scheme11from .exceptions import LocationValueError11from .exceptions import LocationValueError, MaxRetryError12from .request import RequestMethods13from .util.url import parse_url14from .util.retry import Retry15
158 unmodified lines
174 retries = kw.get('retries')175 if not isinstance(retries, Retry):176 retries = Retry.from_int(retries, redirect=redirect)177178 kw['retries'] = retries.increment(method, redirect_location)178 try:179 retries = retries.increment(method, url, response=response, _pool=conn)180 except MaxRetryError:181 if retries.raise_on_redirect:182 raise183 return response184185 kw['retries'] = retries186 kw['redirect'] = redirect187188 log.info("Redirecting %s -> %s" % (url, redirect_location))189 return self.urlopen(method, redirect_location, **kw)
91 unmodified lines
modified:requests/packages/urllib3/response.py+13 added-19 removed
1import zlib2import io3from socket import timeout as SocketTimeout45from .packages import six5from ._collections import HTTPHeaderDict6from .exceptions import ProtocolError, DecodeError, ReadTimeoutError8from .packages.six import string_types as basestring, binary_type7from .packages.six import string_types as basestring, binary_type, PY38from .connection import HTTPException, BaseSSLError9from .util.response import is_fp_closed1011
79 unmodified lines
91 def __init__(self, body='', headers=None, status=0, version=0, reason=None,92 strict=0, preload_content=True, decode_content=True,93 original_response=None, pool=None, connection=None):9496 self.headers = HTTPHeaderDict()97 if headers:98 self.headers.update(headers)95 if isinstance(headers, HTTPHeaderDict):96 self.headers = headers97 else:98 self.headers = HTTPHeaderDict(headers)99 self.status = status100 self.version = version101 self.reason = reason102 self.strict = strict
180 unmodified lines
283284 Remaining parameters are passed to the HTTPResponse constructor, along285 with ``original_response=r``.286 """287 headers = r.msg288 if not isinstance(headers, HTTPHeaderDict):289 if PY3: # Python 3290 headers = HTTPHeaderDict(headers.items())291 else: # Python 2292 headers = HTTPHeaderDict.from_httplib(headers)293288 headers = HTTPHeaderDict()289 for k, v in r.getheaders():290 if k.lower() != 'set-cookie':291 headers.add(k, v)292293 if six.PY3: # Python 3:294 cookies = r.msg.get_all('set-cookie') or tuple()295 else: # Python 2:296 cookies = r.msg.getheaders('set-cookie')297298 for cookie in cookies:299 headers.add('set-cookie', cookie)300294 # HTTPResponse objects in Python 3 don't have a .strict attribute295 strict = getattr(r, 'strict', 0)303 return ResponseCls(body=r,296 resp = ResponseCls(body=r,297 headers=headers,298 status=r.status,299 version=r.version,300 reason=r.reason,301 strict=strict,302 original_response=r,303 **response_kw)304 return resp305306 # Backwards-compatibility methods for httplib.HTTPResponse307 def getheaders(self):308 return self.headers
45 unmodified lines