Skip to content
Myr

Update urllib3 to 1.16

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

authored by Cory Benfield · committed by Cory Benfield · parent cf7fdb9 · Browse files · 11 files+737 added−100 removed
This commit

State

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

Diff stats

11 files+737 added−100 removed

  • other:+737 added−100 removed

11 files+737 added−100 removed

modified:requests/packages/urllib3/contrib/appengine.py+1 added-1 removed
68 unmodified lines
6970 warnings.warn(71 "urllib3 is using URLFetch on Google App Engine sandbox instead "72 "of sockets. To use sockets directly instead of URLFetch see "73 "https://urllib3.readthedocs.org/en/latest/contrib.html.",73 "https://urllib3.readthedocs.io/en/latest/contrib.html.",74 AppEnginePlatformWarning)7576 RequestMethods.__init__(self, headers)77 self.validate_certificate = validate_certificate
154 unmodified lines
modified:requests/packages/urllib3/contrib/socks.py+1 added-1 removed
24 unmodified lines
2526 warnings.warn((27 'SOCKS support in urllib3 requires the installation of optional '28 'dependencies: specifically, PySocks. For more information, see '29 'https://urllib3.readthedocs.org/en/latest/contrib.html#socks-proxies'29 'https://urllib3.readthedocs.io/en/latest/contrib.html#socks-proxies'30 ),31 DependencyWarning32 )33 raise
139 unmodified lines
added:requests/packages/urllib3/packages/ssl_match_hostname/.gitignore+1 added
1env
modified:requests/packages/urllib3/packages/six.py+557 added-74 removed
1"""Utilities for writing code that runs on Python 2 and 3"""23#Copyright (c) 2010-2011 Benjamin Peterson3# Copyright (c) 2010-2015 Benjamin Peterson4#5# Permission is hereby granted, free of charge, to any person obtaining a copy6# of this software and associated documentation files (the "Software"), to deal7# in the Software without restriction, including without limitation the rights8# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell9# copies of the Software, and to permit persons to whom the Software is10# furnished to do so, subject to the following conditions:11#12# The above copyright notice and this permission notice shall be included in all13# copies or substantial portions of the Software.14#15# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR16# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,17# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE18# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER19# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,20# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE21# SOFTWARE.225#Permission is hereby granted, free of charge, to any person obtaining a copy of6#this software and associated documentation files (the "Software"), to deal in7#the Software without restriction, including without limitation the rights to8#use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of9#the Software, and to permit persons to whom the Software is furnished to do so,10#subject to the following conditions:23from __future__ import absolute_import2412#The above copyright notice and this permission notice shall be included in all13#copies or substantial portions of the Software.1415#THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR16#IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS17#FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR18#COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER19#IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN20#CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.2125import functools26import itertools27import operator28import sys29import types3031__author__ = "Benjamin Peterson <benjamin@python.org>"27__version__ = "1.2.0" # Revision 41c74fef2ded32__version__ = "1.10.0"333430# True if we are running on Python 3.35# Useful for very coarse version differentiation.36PY2 = sys.version_info[0] == 237PY3 = sys.version_info[0] == 338PY34 = sys.version_info[0:2] >= (3, 4)3940if PY3:41 string_types = str,42 integer_types = int,
14 unmodified lines
57 MAXSIZE = int((1 << 31) - 1)58 else:59 # It's possible to have sizeof(long) != sizeof(Py_ssize_t).60 class X(object):6162 def __len__(self):63 return 1 << 3164 try:65 len(X())
2 unmodified lines
68 MAXSIZE = int((1 << 31) - 1)69 else:70 # 64-bit71 MAXSIZE = int((1 << 63) - 1)64 del X72 del X737475def _add_doc(func, doc):76 """Add documentation to a function."""
12 unmodified lines
89 self.name = name9091 def __get__(self, obj, tp):92 result = self._resolve()85 setattr(obj, self.name, result)86 # This is a bit ugly, but it avoids running this again.87 delattr(tp, self.name)93 setattr(obj, self.name, result) # Invokes __set__.94 try:95 # This is a bit ugly, but it avoids running this again by96 # removing this descriptor.97 delattr(obj.__class__, self.name)98 except AttributeError:99 pass100 return result101102103class MovedModule(_LazyDescr):
9 unmodified lines
113114 def _resolve(self):115 return _import_module(self.mod)116117 def __getattr__(self, attr):118 _module = self._resolve()119 value = getattr(_module, attr)120 setattr(self, attr, value)121 return value122123124class _LazyModule(types.ModuleType):125126 def __init__(self, name):127 super(_LazyModule, self).__init__(name)128 self.__doc__ = self.__class__.__doc__129130 def __dir__(self):131 attrs = ["__doc__", "__name__"]132 attrs += [attr.name for attr in self._moved_attributes]133 return attrs134135 # Subclasses should override this136 _moved_attributes = []137138139class MovedAttribute(_LazyDescr):140141 def __init__(self, name, old_mod, new_mod, old_attr=None, new_attr=None):142 super(MovedAttribute, self).__init__(name)
17 unmodified lines
160 module = _import_module(self.mod)161 return getattr(module, self.attr)162163164class _SixMetaPathImporter(object):165166 """167 A meta path importer to import six.moves and its submodules.168169 This class implements a PEP302 finder and loader. It should be compatible170 with Python 2.5 and all existing versions of Python3171 """172173 def __init__(self, six_module_name):174 self.name = six_module_name175 self.known_modules = {}176177 def _add_module(self, mod, *fullnames):178 for fullname in fullnames:179 self.known_modules[self.name + "." + fullname] = mod180181 def _get_module(self, fullname):182 return self.known_modules[self.name + "." + fullname]183184 def find_module(self, fullname, path=None):185 if fullname in self.known_modules:186 return self187 return None188189 def __get_module(self, fullname):190 try:191 return self.known_modules[fullname]192 except KeyError:193 raise ImportError("This loader does not know module " + fullname)194195 def load_module(self, fullname):196 try:197 # in case of a reload198 return sys.modules[fullname]199 except KeyError:200 pass201 mod = self.__get_module(fullname)202 if isinstance(mod, MovedModule):203 mod = mod._resolve()204 else:205 mod.__loader__ = self206 sys.modules[fullname] = mod207 return mod208209 def is_package(self, fullname):210 """211 Return true, if the named module is a package.212213 We need this method to get correct spec objects with214 Python 3.4 (see PEP451)215 """216 return hasattr(self.__get_module(fullname), "__path__")217218 def get_code(self, fullname):219 """Return None220221 Required, if is_package is implemented"""222 self.__get_module(fullname) # eventually raises ImportError223 return None224 get_source = get_code # same as get_code225226_importer = _SixMetaPathImporter(__name__)227228132class _MovedItems(types.ModuleType):229class _MovedItems(_LazyModule):230231 """Lazy loading of moved objects"""232 __path__ = [] # mark as package233234235_moved_attributes = [236 MovedAttribute("cStringIO", "cStringIO", "io", "StringIO"),237 MovedAttribute("filter", "itertools", "builtins", "ifilter", "filter"),238 MovedAttribute("filterfalse", "itertools", "itertools", "ifilterfalse", "filterfalse"),239 MovedAttribute("input", "__builtin__", "builtins", "raw_input", "input"),240 MovedAttribute("intern", "__builtin__", "sys"),241 MovedAttribute("map", "itertools", "builtins", "imap", "map"),141 MovedAttribute("reload_module", "__builtin__", "imp", "reload"),242 MovedAttribute("getcwd", "os", "os", "getcwdu", "getcwd"),243 MovedAttribute("getcwdb", "os", "os", "getcwd", "getcwdb"),244 MovedAttribute("range", "__builtin__", "builtins", "xrange", "range"),245 MovedAttribute("reload_module", "__builtin__", "importlib" if PY34 else "imp", "reload"),246 MovedAttribute("reduce", "__builtin__", "functools"),247 MovedAttribute("shlex_quote", "pipes", "shlex", "quote"),248 MovedAttribute("StringIO", "StringIO", "io"),249 MovedAttribute("UserDict", "UserDict", "collections"),250 MovedAttribute("UserList", "UserList", "collections"),251 MovedAttribute("UserString", "UserString", "collections"),252 MovedAttribute("xrange", "__builtin__", "builtins", "xrange", "range"),253 MovedAttribute("zip", "itertools", "builtins", "izip", "zip"),146254 MovedAttribute("zip_longest", "itertools", "itertools", "izip_longest", "zip_longest"),255 MovedModule("builtins", "__builtin__"),256 MovedModule("configparser", "ConfigParser"),257 MovedModule("copyreg", "copy_reg"),258 MovedModule("dbm_gnu", "gdbm", "dbm.gnu"),259 MovedModule("_dummy_thread", "dummy_thread", "_dummy_thread"),260 MovedModule("http_cookiejar", "cookielib", "http.cookiejar"),261 MovedModule("http_cookies", "Cookie", "http.cookies"),262 MovedModule("html_entities", "htmlentitydefs", "html.entities"),263 MovedModule("html_parser", "HTMLParser", "html.parser"),264 MovedModule("http_client", "httplib", "http.client"),265 MovedModule("email_mime_multipart", "email.MIMEMultipart", "email.mime.multipart"),266 MovedModule("email_mime_nonmultipart", "email.MIMENonMultipart", "email.mime.nonmultipart"),267 MovedModule("email_mime_text", "email.MIMEText", "email.mime.text"),268 MovedModule("email_mime_base", "email.MIMEBase", "email.mime.base"),269 MovedModule("BaseHTTPServer", "BaseHTTPServer", "http.server"),270 MovedModule("CGIHTTPServer", "CGIHTTPServer", "http.server"),271 MovedModule("SimpleHTTPServer", "SimpleHTTPServer", "http.server"),272 MovedModule("cPickle", "cPickle", "pickle"),273 MovedModule("queue", "Queue"),274 MovedModule("reprlib", "repr"),275 MovedModule("socketserver", "SocketServer"),276 MovedModule("_thread", "thread", "_thread"),277 MovedModule("tkinter", "Tkinter"),278 MovedModule("tkinter_dialog", "Dialog", "tkinter.dialog"),279 MovedModule("tkinter_filedialog", "FileDialog", "tkinter.filedialog"),280 MovedModule("tkinter_scrolledtext", "ScrolledText", "tkinter.scrolledtext"),281 MovedModule("tkinter_simpledialog", "SimpleDialog", "tkinter.simpledialog"),282 MovedModule("tkinter_tix", "Tix", "tkinter.tix"),283 MovedModule("tkinter_ttk", "ttk", "tkinter.ttk"),284 MovedModule("tkinter_constants", "Tkconstants", "tkinter.constants"),285 MovedModule("tkinter_dnd", "Tkdnd", "tkinter.dnd"),286 MovedModule("tkinter_colorchooser", "tkColorChooser",287 "tkinter.colorchooser"),
3 unmodified lines
291 MovedModule("tkinter_font", "tkFont", "tkinter.font"),292 MovedModule("tkinter_messagebox", "tkMessageBox", "tkinter.messagebox"),293 MovedModule("tkinter_tksimpledialog", "tkSimpleDialog",294 "tkinter.simpledialog"),295 MovedModule("urllib_parse", __name__ + ".moves.urllib_parse", "urllib.parse"),296 MovedModule("urllib_error", __name__ + ".moves.urllib_error", "urllib.error"),297 MovedModule("urllib", __name__ + ".moves.urllib", __name__ + ".moves.urllib"),298 MovedModule("urllib_robotparser", "robotparser", "urllib.robotparser"),180 MovedModule("winreg", "_winreg"),299 MovedModule("xmlrpc_client", "xmlrpclib", "xmlrpc.client"),300 MovedModule("xmlrpc_server", "SimpleXMLRPCServer", "xmlrpc.server"),301]302# Add windows specific modules.303if sys.platform == "win32":304 _moved_attributes += [305 MovedModule("winreg", "_winreg"),306 ]307308for attr in _moved_attributes:309 setattr(_MovedItems, attr.name, attr)310 if isinstance(attr, MovedModule):311 _importer._add_module(attr, "moves." + attr.name)312del attr313186moves = sys.modules[__name__ + ".moves"] = _MovedItems("moves")314_MovedItems._moved_attributes = _moved_attributes315316moves = _MovedItems(__name__ + ".moves")317_importer._add_module(moves, "moves")318319320class Module_six_moves_urllib_parse(_LazyModule):321322 """Lazy loading of moved objects in six.moves.urllib_parse"""323324325_urllib_parse_moved_attributes = [326 MovedAttribute("ParseResult", "urlparse", "urllib.parse"),327 MovedAttribute("SplitResult", "urlparse", "urllib.parse"),328 MovedAttribute("parse_qs", "urlparse", "urllib.parse"),329 MovedAttribute("parse_qsl", "urlparse", "urllib.parse"),330 MovedAttribute("urldefrag", "urlparse", "urllib.parse"),331 MovedAttribute("urljoin", "urlparse", "urllib.parse"),332 MovedAttribute("urlparse", "urlparse", "urllib.parse"),333 MovedAttribute("urlsplit", "urlparse", "urllib.parse"),334 MovedAttribute("urlunparse", "urlparse", "urllib.parse"),335 MovedAttribute("urlunsplit", "urlparse", "urllib.parse"),336 MovedAttribute("quote", "urllib", "urllib.parse"),337 MovedAttribute("quote_plus", "urllib", "urllib.parse"),338 MovedAttribute("unquote", "urllib", "urllib.parse"),339 MovedAttribute("unquote_plus", "urllib", "urllib.parse"),340 MovedAttribute("urlencode", "urllib", "urllib.parse"),341 MovedAttribute("splitquery", "urllib", "urllib.parse"),342 MovedAttribute("splittag", "urllib", "urllib.parse"),343 MovedAttribute("splituser", "urllib", "urllib.parse"),344 MovedAttribute("uses_fragment", "urlparse", "urllib.parse"),345 MovedAttribute("uses_netloc", "urlparse", "urllib.parse"),346 MovedAttribute("uses_params", "urlparse", "urllib.parse"),347 MovedAttribute("uses_query", "urlparse", "urllib.parse"),348 MovedAttribute("uses_relative", "urlparse", "urllib.parse"),349]350for attr in _urllib_parse_moved_attributes:351 setattr(Module_six_moves_urllib_parse, attr.name, attr)352del attr353354Module_six_moves_urllib_parse._moved_attributes = _urllib_parse_moved_attributes355356_importer._add_module(Module_six_moves_urllib_parse(__name__ + ".moves.urllib_parse"),357 "moves.urllib_parse", "moves.urllib.parse")358359360class Module_six_moves_urllib_error(_LazyModule):361362 """Lazy loading of moved objects in six.moves.urllib_error"""363364365_urllib_error_moved_attributes = [366 MovedAttribute("URLError", "urllib2", "urllib.error"),367 MovedAttribute("HTTPError", "urllib2", "urllib.error"),368 MovedAttribute("ContentTooShortError", "urllib", "urllib.error"),369]370for attr in _urllib_error_moved_attributes:371 setattr(Module_six_moves_urllib_error, attr.name, attr)372del attr373374Module_six_moves_urllib_error._moved_attributes = _urllib_error_moved_attributes375376_importer._add_module(Module_six_moves_urllib_error(__name__ + ".moves.urllib.error"),377 "moves.urllib_error", "moves.urllib.error")378379380class Module_six_moves_urllib_request(_LazyModule):381382 """Lazy loading of moved objects in six.moves.urllib_request"""383384385_urllib_request_moved_attributes = [386 MovedAttribute("urlopen", "urllib2", "urllib.request"),387 MovedAttribute("install_opener", "urllib2", "urllib.request"),388 MovedAttribute("build_opener", "urllib2", "urllib.request"),389 MovedAttribute("pathname2url", "urllib", "urllib.request"),390 MovedAttribute("url2pathname", "urllib", "urllib.request"),391 MovedAttribute("getproxies", "urllib", "urllib.request"),392 MovedAttribute("Request", "urllib2", "urllib.request"),393 MovedAttribute("OpenerDirector", "urllib2", "urllib.request"),394 MovedAttribute("HTTPDefaultErrorHandler", "urllib2", "urllib.request"),395 MovedAttribute("HTTPRedirectHandler", "urllib2", "urllib.request"),396 MovedAttribute("HTTPCookieProcessor", "urllib2", "urllib.request"),397 MovedAttribute("ProxyHandler", "urllib2", "urllib.request"),398 MovedAttribute("BaseHandler", "urllib2", "urllib.request"),399 MovedAttribute("HTTPPasswordMgr", "urllib2", "urllib.request"),400 MovedAttribute("HTTPPasswordMgrWithDefaultRealm", "urllib2", "urllib.request"),401 MovedAttribute("AbstractBasicAuthHandler", "urllib2", "urllib.request"),402 MovedAttribute("HTTPBasicAuthHandler", "urllib2", "urllib.request"),403 MovedAttribute("ProxyBasicAuthHandler", "urllib2", "urllib.request"),404 MovedAttribute("AbstractDigestAuthHandler", "urllib2", "urllib.request"),405 MovedAttribute("HTTPDigestAuthHandler", "urllib2", "urllib.request"),406 MovedAttribute("ProxyDigestAuthHandler", "urllib2", "urllib.request"),407 MovedAttribute("HTTPHandler", "urllib2", "urllib.request"),408 MovedAttribute("HTTPSHandler", "urllib2", "urllib.request"),409 MovedAttribute("FileHandler", "urllib2", "urllib.request"),410 MovedAttribute("FTPHandler", "urllib2", "urllib.request"),411 MovedAttribute("CacheFTPHandler", "urllib2", "urllib.request"),412 MovedAttribute("UnknownHandler", "urllib2", "urllib.request"),413 MovedAttribute("HTTPErrorProcessor", "urllib2", "urllib.request"),414 MovedAttribute("urlretrieve", "urllib", "urllib.request"),415 MovedAttribute("urlcleanup", "urllib", "urllib.request"),416 MovedAttribute("URLopener", "urllib", "urllib.request"),417 MovedAttribute("FancyURLopener", "urllib", "urllib.request"),418 MovedAttribute("proxy_bypass", "urllib", "urllib.request"),419]420for attr in _urllib_request_moved_attributes:421 setattr(Module_six_moves_urllib_request, attr.name, attr)422del attr423424Module_six_moves_urllib_request._moved_attributes = _urllib_request_moved_attributes425426_importer._add_module(Module_six_moves_urllib_request(__name__ + ".moves.urllib.request"),427 "moves.urllib_request", "moves.urllib.request")428429430class Module_six_moves_urllib_response(_LazyModule):431432 """Lazy loading of moved objects in six.moves.urllib_response"""433434435_urllib_response_moved_attributes = [436 MovedAttribute("addbase", "urllib", "urllib.response"),437 MovedAttribute("addclosehook", "urllib", "urllib.response"),438 MovedAttribute("addinfo", "urllib", "urllib.response"),439 MovedAttribute("addinfourl", "urllib", "urllib.response"),440]441for attr in _urllib_response_moved_attributes:442 setattr(Module_six_moves_urllib_response, attr.name, attr)443del attr444445Module_six_moves_urllib_response._moved_attributes = _urllib_response_moved_attributes446447_importer._add_module(Module_six_moves_urllib_response(__name__ + ".moves.urllib.response"),448 "moves.urllib_response", "moves.urllib.response")449450451class Module_six_moves_urllib_robotparser(_LazyModule):452453 """Lazy loading of moved objects in six.moves.urllib_robotparser"""454455456_urllib_robotparser_moved_attributes = [457 MovedAttribute("RobotFileParser", "robotparser", "urllib.robotparser"),458]459for attr in _urllib_robotparser_moved_attributes:460 setattr(Module_six_moves_urllib_robotparser, attr.name, attr)461del attr462463Module_six_moves_urllib_robotparser._moved_attributes = _urllib_robotparser_moved_attributes464465_importer._add_module(Module_six_moves_urllib_robotparser(__name__ + ".moves.urllib.robotparser"),466 "moves.urllib_robotparser", "moves.urllib.robotparser")467468469class Module_six_moves_urllib(types.ModuleType):470471 """Create a six.moves.urllib namespace that resembles the Python 3 namespace"""472 __path__ = [] # mark as package473 parse = _importer._get_module("moves.urllib_parse")474 error = _importer._get_module("moves.urllib_error")475 request = _importer._get_module("moves.urllib_request")476 response = _importer._get_module("moves.urllib_response")477 robotparser = _importer._get_module("moves.urllib_robotparser")478479 def __dir__(self):480 return ['parse', 'error', 'request', 'response', 'robotparser']481482_importer._add_module(Module_six_moves_urllib(__name__ + ".moves.urllib"),483 "moves.urllib")484485486def add_move(move):487 """Add an item to six.moves."""488 setattr(_MovedItems, move.name, move)489
12 unmodified lines
502if PY3:503 _meth_func = "__func__"504 _meth_self = "__self__"505506 _func_closure = "__closure__"507 _func_code = "__code__"508 _func_defaults = "__defaults__"211212 _iterkeys = "keys"213 _itervalues = "values"214 _iteritems = "items"509 _func_globals = "__globals__"510else:511 _meth_func = "im_func"512 _meth_self = "im_self"513514 _func_closure = "func_closure"515 _func_code = "func_code"516 _func_defaults = "func_defaults"517 _func_globals = "func_globals"518222 _iterkeys = "iterkeys"223 _itervalues = "itervalues"224 _iteritems = "iteritems"519226520try:521 advance_iterator = next522except NameError:523 def advance_iterator(it):524 return it.next()525next = advance_iterator526527528try:529 callable = callable530except NameError:531 def callable(obj):532 return any("__call__" in klass.__dict__ for klass in type(obj).__mro__)533534535if PY3:536 def get_unbound_function(unbound):537 return unbound538239 Iterator = object539 create_bound_method = types.MethodType540241 def callable(obj):242 return any("__call__" in klass.__dict__ for klass in type(obj).__mro__)541 def create_unbound_method(func, cls):542 return func543544 Iterator = object545else:546 def get_unbound_function(unbound):547 return unbound.im_func548549 def create_bound_method(func, obj):550 return types.MethodType(func, obj, obj.__class__)551552 def create_unbound_method(func, cls):553 return types.MethodType(func, None, cls)554555 class Iterator(object):556557 def next(self):558 return type(self).__next__(self)
4 unmodified lines
563564565get_method_function = operator.attrgetter(_meth_func)566get_method_self = operator.attrgetter(_meth_self)567get_function_closure = operator.attrgetter(_func_closure)568get_function_code = operator.attrgetter(_func_code)569get_function_defaults = operator.attrgetter(_func_defaults)570get_function_globals = operator.attrgetter(_func_globals)571572263def iterkeys(d):264 """Return an iterator over the keys of a dictionary."""265 return iter(getattr(d, _iterkeys)())573if PY3:574 def iterkeys(d, **kw):575 return iter(d.keys(**kw))576267def itervalues(d):268 """Return an iterator over the values of a dictionary."""269 return iter(getattr(d, _itervalues)())577 def itervalues(d, **kw):578 return iter(d.values(**kw))579271def iteritems(d):272 """Return an iterator over the (key, value) pairs of a dictionary."""273 return iter(getattr(d, _iteritems)())580 def iteritems(d, **kw):581 return iter(d.items(**kw))582583 def iterlists(d, **kw):584 return iter(d.lists(**kw))585586 viewkeys = operator.methodcaller("keys")587588 viewvalues = operator.methodcaller("values")589590 viewitems = operator.methodcaller("items")591else:592 def iterkeys(d, **kw):593 return d.iterkeys(**kw)594595 def itervalues(d, **kw):596 return d.itervalues(**kw)597598 def iteritems(d, **kw):599 return d.iteritems(**kw)600601 def iterlists(d, **kw):602 return d.iterlists(**kw)603604 viewkeys = operator.methodcaller("viewkeys")605606 viewvalues = operator.methodcaller("viewvalues")607608 viewitems = operator.methodcaller("viewitems")609610_add_doc(iterkeys, "Return an iterator over the keys of a dictionary.")611_add_doc(itervalues, "Return an iterator over the values of a dictionary.")612_add_doc(iteritems,613 "Return an iterator over the (key, value) pairs of a dictionary.")614_add_doc(iterlists,615 "Return an iterator over the (key, [values]) pairs of a dictionary.")616617618if PY3:619 def b(s):620 return s.encode("latin-1")621622 def u(s):623 return s281 if sys.version_info[1] <= 1:282 def int2byte(i):283 return bytes((i,))284 else:285 # This is about 2x faster than the implementation above on 3.2+286 int2byte = operator.methodcaller("to_bytes", 1, "big")624 unichr = chr625 import struct626 int2byte = struct.Struct(">B").pack627 del struct628 byte2int = operator.itemgetter(0)629 indexbytes = operator.getitem630 iterbytes = iter631 import io632 StringIO = io.StringIO633 BytesIO = io.BytesIO634 _assertCountEqual = "assertCountEqual"635 if sys.version_info[1] <= 1:636 _assertRaisesRegex = "assertRaisesRegexp"637 _assertRegex = "assertRegexpMatches"638 else:639 _assertRaisesRegex = "assertRaisesRegex"640 _assertRegex = "assertRegex"641else:642 def b(s):643 return s644 # Workaround for standalone backslash645646 def u(s):294 return unicode(s, "unicode_escape")647 return unicode(s.replace(r'\\', r'\\\\'), "unicode_escape")648 unichr = unichr649 int2byte = chr650651 def byte2int(bs):652 return ord(bs[0])653654 def indexbytes(buf, i):655 return ord(buf[i])656 iterbytes = functools.partial(itertools.imap, ord)657 import StringIO658 StringIO = BytesIO = StringIO.StringIO659 _assertCountEqual = "assertItemsEqual"660 _assertRaisesRegex = "assertRaisesRegexp"661 _assertRegex = "assertRegexpMatches"662_add_doc(b, """Byte literal""")663_add_doc(u, """Text literal""")664665302if PY3:303 import builtins304 exec_ = getattr(builtins, "exec")666def assertCountEqual(self, *args, **kwargs):667 return getattr(self, _assertCountEqual)(*args, **kwargs)668669670def assertRaisesRegex(self, *args, **kwargs):671 return getattr(self, _assertRaisesRegex)(*args, **kwargs)672673674def assertRegex(self, *args, **kwargs):675 return getattr(self, _assertRegex)(*args, **kwargs)676677678if PY3:679 exec_ = getattr(moves.builtins, "exec")680681 def reraise(tp, value, tb=None):682 if value is None:683 value = tp()684 if value.__traceback__ is not tb:685 raise value.with_traceback(tb)686 raise value687312313 print_ = getattr(builtins, "print")314 del builtins315688else:317 def exec_(code, globs=None, locs=None):689 def exec_(_code_, _globs_=None, _locs_=None):690 """Execute code in a namespace."""319 if globs is None:691 if _globs_ is None:692 frame = sys._getframe(1)321 globs = frame.f_globals322 if locs is None:323 locs = frame.f_locals693 _globs_ = frame.f_globals694 if _locs_ is None:695 _locs_ = frame.f_locals696 del frame325 elif locs is None:326 locs = globs327 exec("""exec code in globs, locs""")697 elif _locs_ is None:698 _locs_ = _globs_699 exec("""exec _code_ in _globs_, _locs_""")700329701 exec_("""def reraise(tp, value, tb=None):702 raise tp, value, tb703""")704705706if sys.version_info[:2] == (3, 2):707 exec_("""def raise_from(value, from_value):708 if from_value is None:709 raise value710 raise value from from_value711""")712elif sys.version_info[:2] > (3, 2):713 exec_("""def raise_from(value, from_value):714 raise value from from_value715""")716else:717 def raise_from(value, from_value):718 raise value719720721print_ = getattr(moves.builtins, "print", None)722if print_ is None:723 def print_(*args, **kwargs):336 """The new-style print function."""724 """The new-style print function for Python 2.4 and 2.5."""725 fp = kwargs.pop("file", sys.stdout)726 if fp is None:727 return728729 def write(data):730 if not isinstance(data, basestring):731 data = str(data)732 # If the file has an encoding, encode unicode with it.733 if (isinstance(fp, file) and734 isinstance(data, unicode) and735 fp.encoding is not None):736 errors = getattr(fp, "errors", None)737 if errors is None:738 errors = "strict"739 data = data.encode(fp.encoding, errors)740 fp.write(data)741 want_unicode = False742 sep = kwargs.pop("sep", None)743 if sep is not None:
28 unmodified lines
772 if i:773 write(sep)774 write(arg)775 write(end)776if sys.version_info[:2] < (3, 3):777 _print = print_778779 def print_(*args, **kwargs):780 fp = kwargs.get("file", sys.stdout)781 flush = kwargs.pop("flush", False)782 _print(*args, **kwargs)783 if flush and fp is not None:784 fp.flush()785786_add_doc(reraise, """Reraise an exception.""")787788if sys.version_info[0:2] < (3, 4):789 def wraps(wrapped, assigned=functools.WRAPPER_ASSIGNMENTS,790 updated=functools.WRAPPER_UPDATES):791 def wrapper(f):792 f = functools.wraps(wrapped, assigned, updated)(f)793 f.__wrapped__ = wrapped794 return f795 return wrapper796else:797 wraps = functools.wraps798799383def with_metaclass(meta, base=object):800def with_metaclass(meta, *bases):801 """Create a base class with a metaclass."""385 return meta("NewBase", (base,), {})802 # This requires a bit of explanation: the basic idea is to make a dummy803 # metaclass for one level of class instantiation that replaces itself with804 # the actual metaclass.805 class metaclass(meta):806807 def __new__(cls, name, this_bases, d):808 return meta(name, bases, d)809 return type.__new__(metaclass, 'temporary_class', (), {})810811812def add_metaclass(metaclass):813 """Class decorator for creating a class with a metaclass."""814 def wrapper(cls):815 orig_vars = cls.__dict__.copy()816 slots = orig_vars.get('__slots__')817 if slots is not None:818 if isinstance(slots, str):819 slots = [slots]820 for slots_var in slots:821 orig_vars.pop(slots_var)822 orig_vars.pop('__dict__', None)823 orig_vars.pop('__weakref__', None)824 return metaclass(cls.__name__, cls.__bases__, orig_vars)825 return wrapper826827828def python_2_unicode_compatible(klass):829 """830 A decorator that defines __unicode__ and __str__ methods under Python 2.831 Under Python 3 it does nothing.832833 To support Python 2 and 3 with a single code base, define a __str__ method834 returning text and apply this decorator to the class.835 """836 if PY2:837 if '__str__' not in klass.__dict__:838 raise ValueError("@python_2_unicode_compatible cannot be applied "839 "to %s because it doesn't define __str__()." %840 klass.__name__)841 klass.__unicode__ = klass.__str__842 klass.__str__ = lambda self: self.__unicode__().encode('utf-8')843 return klass844845846# Complete the moves implementation.847# This code is at the end of this module to speed up module loading.848# Turn this module into a package.849__path__ = [] # required for PEP 302 and PEP 451850__package__ = __name__ # see PEP 366 @ReservedAssignment851if globals().get("__spec__") is not None:852 __spec__.submodule_search_locations = [] # PEP 451 @UndefinedVariable853# Remove other six meta path importers, since they cause problems. This can854# happen if six is removed from sys.modules and then reloaded. (Setuptools does855# this for some reason.)856if sys.meta_path:857 for i, importer in enumerate(sys.meta_path):858 # Here's some real nastiness: Another "instance" of the six module might859 # be floating around. Therefore, we can't use isinstance() to check for860 # the six meta path importer, since the other six instance will have861 # inserted an importer with different class.862 if (type(importer).__name__ == "_SixMetaPathImporter" and863 importer.name == __name__):864 del sys.meta_path[i]865 break866 del i, importer867# Finally, add the importer to the meta path import hook.868sys.meta_path.append(_importer)
modified:requests/packages/urllib3/util/connection.py+45 added-2 removed
44 unmodified lines
454647# This function is copied from socket.py in the Python 2.7 standard48# library test suite. Added to its signature is only `socket_options`.49# One additional modification is that we avoid binding to IPv6 servers50# discovered in DNS if the system doesn't have IPv6 functionality.51def create_connection(address, timeout=socket._GLOBAL_DEFAULT_TIMEOUT,52 source_address=None, socket_options=None):53 """Connect to *address* and return the socket object.54
10 unmodified lines
65 host, port = address66 if host.startswith('['):67 host = host.strip('[]')68 err = None6970 # Using the value from allowed_gai_family() in the context of getaddrinfo lets71 # us select whether to work with IPv4 DNS records, IPv6 records, or both.72 # The original create_connection function always returns all records.73 family = allowed_gai_family()7467 for res in socket.getaddrinfo(host, port, 0, socket.SOCK_STREAM):75 for res in socket.getaddrinfo(host, port, family, socket.SOCK_STREAM):76 af, socktype, proto, canonname, sa = res77 sock = None78 try:79 sock = socket.socket(af, socktype, proto)8081 # If provided, set socket level options before connecting.74 # This is the only addition urllib3 makes to this function.82 _set_socket_options(sock, socket_options)8384 if timeout is not socket._GLOBAL_DEFAULT_TIMEOUT:85 sock.settimeout(timeout)
19 unmodified lines
105 return106107 for opt in options:108 sock.setsockopt(*opt)109110111def allowed_gai_family():112 """This function is designed to work in the context of113 getaddrinfo, where family=socket.AF_UNSPEC is the default and114 will perform a DNS search for both IPv6 and IPv4 records."""115116 family = socket.AF_INET117 if HAS_IPV6:118 family = socket.AF_UNSPEC119 return family120121122def _has_ipv6(host):123 """ Returns True if the system can bind an IPv6 address. """124 sock = None125 has_ipv6 = False126127 if socket.has_ipv6:128 # has_ipv6 returns true if cPython was compiled with IPv6 support.129 # It does not tell us if the system has IPv6 support enabled. To130 # determine that we must bind to an IPv6 address.131 # https://github.com/shazow/urllib3/pull/611132 # https://bugs.python.org/issue658327133 try:134 sock = socket.socket(socket.AF_INET6)135 sock.bind((host, 0))136 has_ipv6 = True137 except Exception:138 pass139140 if sock:141 sock.close()142 return has_ipv6143144HAS_IPV6 = _has_ipv6('::1')
modified:requests/packages/urllib3/util/retry.py+10 added-4 removed
78 unmodified lines
79 :param iterable method_whitelist:80 Set of uppercased HTTP method verbs that we should retry on.8182 By default, we only retry on methods which are considered to be83 indempotent (multiple requests with the same parameters end with the83 idempotent (multiple requests with the same parameters end with the84 same state). See :attr:`Retry.DEFAULT_METHOD_WHITELIST`.8586 Set to a ``False`` value to retry on any verb.8788 :param iterable status_forcelist:87 A set of HTTP status codes that we should force a retry on.89 A set of integer HTTP status codes that we should force a retry on.90 A retry is initiated if the request method is in ``method_whitelist``91 and the response status code is in ``status_forcelist``.9293 By default, this is disabled with ``None``.9495 :param float backoff_factor:92 A backoff factor to apply between attempts. urllib3 will sleep for::96 A backoff factor to apply between attempts after the second try97 (most errors are resolved immediately by a second try without a98 delay). urllib3 will sleep for::99100 {backoff factor} * (2 ^ ({number of total retries} - 1))101102 seconds. If the backoff_factor is 0.1, then :func:`.sleep` will sleep97 for [0.1s, 0.2s, 0.4s, ...] between retries. It will never be longer103 for [0.0s, 0.2s, 0.4s, ...] between retries. It will never be longer104 than :attr:`Retry.BACKOFF_MAX`.105106 By default, backoff is disabled (set to 0).107
193 unmodified lines
modified:requests/packages/urllib3/util/ssl_.py+2 added-2 removed
115 unmodified lines
116 'A true SSLContext object is not available. This prevents '117 'urllib3 from configuring SSL appropriately and may cause '118 'certain SSL connections to fail. You can upgrade to a newer '119 'version of Python to solve this. For more information, see '120 'https://urllib3.readthedocs.org/en/latest/security.html'120 'https://urllib3.readthedocs.io/en/latest/security.html'121 '#insecureplatformwarning.',122 InsecurePlatformWarning123 )124 kwargs = {
187 unmodified lines
312 'Indication) extension to TLS is not available on this platform. '313 'This may cause the server to present an incorrect TLS '314 'certificate, which can cause validation failures. You can upgrade to '315 'a newer version of Python to solve this. For more information, see '316 'https://urllib3.readthedocs.org/en/latest/security.html'316 'https://urllib3.readthedocs.io/en/latest/security.html'317 '#snimissingwarning.',318 SNIMissingWarning319 )320 return context.wrap_socket(sock)
modified:requests/packages/urllib3/__init__.py+1 added-1 removed
30 unmodified lines
31 pass3233__author__ = 'Andrey Petrov (andrey.petrov@shazow.net)'34__license__ = 'MIT'35__version__ = '1.15.1'35__version__ = '1.16'3637__all__ = (38 'HTTPConnectionPool',39 'HTTPSConnectionPool',
57 unmodified lines
modified:requests/packages/urllib3/connectionpool.py+27 added-10 removed
88 unmodified lines
89 self.close()90 # Return False to re-raise any potential exceptions91 return False9293 def close():93 def close(self):94 """95 Close all pooled connections and disable the pool.96 """97 pass
64 unmodified lines
162 """163164 scheme = 'http'165 ConnectionCls = HTTPConnection166 ResponseCls = HTTPResponse167168 def __init__(self, host, port=None, strict=False,169 timeout=Timeout.DEFAULT_TIMEOUT, maxsize=1, block=False,170 headers=None, retries=None,
212 unmodified lines
383 # Receive the response from the server384 try:385 try: # Python 2.7, use buffering of HTTP responses386 httplib_response = conn.getresponse(buffering=True)386 except TypeError: # Python 2.6 and older387 httplib_response = conn.getresponse()387 except TypeError: # Python 2.6 and older, Python 3388 try:389 httplib_response = conn.getresponse()390 except Exception as e:391 # Remove the TypeError from the exception chain in Python 3;392 # otherwise it looks like a programming error was the cause.393 six.raise_from(e, None)394 except (SocketTimeout, BaseSSLError, SocketError) as e:395 self._raise_timeout(err=e, url=url, timeout_value=read_timeout)396 raise397
152 unmodified lines
550 raise HostChangedError(self, url, retries)551552 conn = None553554 # Track whether `conn` needs to be released before555 # returning/raising/recursing. Update this variable if necessary, and556 # leave `release_conn` constant throughout the function. That way, if557 # the function recurses, the original value of `release_conn` will be558 # passed down into the recursive call, and its value will be respected.559 #560 # See issue #651 [1] for details.561 #562 # [1] <https://github.com/shazow/urllib3/issues/651>563 release_this_conn = release_conn564565 # Merge the proxy headers. Only do this in HTTP. We have to copy the566 # headers dict so we can safely change it without those changes being567 # reflected in anyone else's copy.568 if self.scheme == 'http':
31 unmodified lines
600 # mess.601 response_conn = conn if not release_conn else None602603 # Import httplib's response into our own wrapper object587 response = HTTPResponse.from_httplib(httplib_response,588 pool=self,589 connection=response_conn,590 **response_kw)604 response = self.ResponseCls.from_httplib(httplib_response,605 pool=self,606 connection=response_conn,607 **response_kw)608609 # Everything went great!610 clean_exit = True611
37 unmodified lines
649 # to throw the connection away unless explicitly told not to.650 # Close the connection, set the variable to None, and make sure651 # we put the None back in the pool to avoid leaking it.652 conn = conn and conn.close()636 release_conn = True653 release_this_conn = True654638 if release_conn:655 if release_this_conn:656 # Put the connection back to be reused. If the connection is657 # expired then it will be None, which will get replaced with a658 # fresh connection during _get_conn.659 self._put_conn(conn)
173 unmodified lines
833 if not conn.is_verified:834 warnings.warn((835 'Unverified HTTPS request is being made. '836 'Adding certificate verification is strongly advised. See: '820 'https://urllib3.readthedocs.org/en/latest/security.html'),837 'https://urllib3.readthedocs.io/en/latest/security.html'),838 InsecureRequestWarning)839840841def connection_from_url(url, **kw):
25 unmodified lines
modified:requests/packages/urllib3/poolmanager.py+88 added-5 removed
1from __future__ import absolute_import2import collections3import functools4import logging56try: # Python 37 from urllib.parse import urljoin
16 unmodified lines
2425SSL_KEYWORDS = ('key_file', 'cert_file', 'cert_reqs', 'ca_certs',26 'ssl_version', 'ca_cert_dir')2728# The base fields to use when determining what pool to get a connection from;29# these do not rely on the ``connection_pool_kw`` and can be determined by the30# URL and potentially the ``urllib3.connection.port_by_scheme`` dictionary.31#32# All custom key schemes should include the fields in this key at a minimum.33BasePoolKey = collections.namedtuple('BasePoolKey', ('scheme', 'host', 'port'))3435# The fields to use when determining what pool to get a HTTP and HTTPS36# connection from. All additional fields must be present in the PoolManager's37# ``connection_pool_kw`` instance variable.38HTTPPoolKey = collections.namedtuple(39 'HTTPPoolKey', BasePoolKey._fields + ('timeout', 'retries', 'strict',40 'block', 'source_address')41)42HTTPSPoolKey = collections.namedtuple(43 'HTTPSPoolKey', HTTPPoolKey._fields + SSL_KEYWORDS44)454647def _default_key_normalizer(key_class, request_context):48 """49 Create a pool key of type ``key_class`` for a request.5051 According to RFC 3986, both the scheme and host are case-insensitive.52 Therefore, this function normalizes both before constructing the pool53 key for an HTTPS request. If you wish to change this behaviour, provide54 alternate callables to ``key_fn_by_scheme``.5556 :param key_class:57 The class to use when constructing the key. This should be a namedtuple58 with the ``scheme`` and ``host`` keys at a minimum.5960 :param request_context:61 A dictionary-like object that contain the context for a request.62 It should contain a key for each field in the :class:`HTTPPoolKey`63 """64 context = {}65 for key in key_class._fields:66 context[key] = request_context.get(key)67 context['scheme'] = context['scheme'].lower()68 context['host'] = context['host'].lower()69 return key_class(**context)707172# A dictionary that maps a scheme to a callable that creates a pool key.73# This can be used to alter the way pool keys are constructed, if desired.74# Each PoolManager makes a copy of this dictionary so they can be configured75# globally here, or individually on the instance.76key_fn_by_scheme = {77 'http': functools.partial(_default_key_normalizer, HTTPPoolKey),78 'https': functools.partial(_default_key_normalizer, HTTPSPoolKey),79}8081pool_classes_by_scheme = {82 'http': HTTPConnectionPool,83 'https': HTTPSConnectionPool,84}
34 unmodified lines
119 self.connection_pool_kw = connection_pool_kw120 self.pools = RecentlyUsedContainer(num_pools,121 dispose_func=lambda p: p.close())12268 # Locally set the pool classes so other PoolManagers can override them.123 # Locally set the pool classes and keys so other PoolManagers can124 # override them.125 self.pool_classes_by_scheme = pool_classes_by_scheme126 self.key_fn_by_scheme = key_fn_by_scheme.copy()127128 def __enter__(self):129 return self130
38 unmodified lines
169170 if not host:171 raise LocationValueError("No host specified.")172116 scheme = scheme or 'http'117 port = port or port_by_scheme.get(scheme, 80)118 pool_key = (scheme, host, port)173 request_context = self.connection_pool_kw.copy()174 request_context['scheme'] = scheme or 'http'175 if not port:176 port = port_by_scheme.get(request_context['scheme'].lower(), 80)177 request_context['port'] = port178 request_context['host'] = host179180 return self.connection_from_context(request_context)181182 def connection_from_context(self, request_context):183 """184 Get a :class:`ConnectionPool` based on the request context.185186 ``request_context`` must at least contain the ``scheme`` key and its187 value must be a key in ``key_fn_by_scheme`` instance variable.188 """189 scheme = request_context['scheme'].lower()190 pool_key_constructor = self.key_fn_by_scheme[scheme]191 pool_key = pool_key_constructor(request_context)192193 return self.connection_from_pool_key(pool_key)194195 def connection_from_pool_key(self, pool_key):196 """197 Get a :class:`ConnectionPool` based on the provided pool key.198199 ``pool_key`` should be a namedtuple that only contains immutable200 objects. At a minimum it must have the ``scheme``, ``host``, and201 ``port`` fields.202 """203 with self.pools.lock:204 # If the scheme, host, or port doesn't match existing open205 # connections, open a new ConnectionPool.206 pool = self.pools.get(pool_key)207 if pool:208 return pool209210 # Make a fresh ConnectionPool of the desired type128 pool = self._new_pool(scheme, host, port)211 pool = self._new_pool(pool_key.scheme, pool_key.host, pool_key.port)212 self.pools[pool_key] = pool213214 return pool215
152 unmodified lines
modified:requests/packages/urllib3/response.py+4 added
163 unmodified lines
164165 if self._fp:166 return self.read(cache_content=True)167168 @property169 def connection(self):170 return self._connection171172 def tell(self):173 """174 Obtain the number of bytes pulled over the wire so far. May differ from175 the amount of content returned by :meth:``HTTPResponse.read`` if bytes
355 unmodified lines