python3 version of urllib3
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by Kenneth Reitz · committed by Kenneth Reitz · parent 62d05f8 · Browse files · 10 files·+437 added−45 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
10 files+437 added−45 removed
- other:+437 added−45 removed
Provenance
- Commit
786dfdd- Tree
3c63e3d- Author
Kenneth Reitz <me@kennethreitz.com>- Committer
Kenneth Reitz <me@kennethreitz.com>- Parent
62d05f8
10 files changed+437 added−45 removed
modified:requests/packages/urllib3/contrib/ntlmpool.py+6 added-3 removed
1 # urllib3/contrib/ntlmpool.py2-# Copyright 2008-2011 Andrey Petrov and contributors (see CONTRIBUTORS.txt)2+# Copyright 2008-2012 Andrey Petrov and contributors (see CONTRIBUTORS.txt)3 #4 # This module is part of urllib3 and is released under5 # the MIT License: http://www.opensource.org/licenses/mit-license.php6 2 unmodified lines9 10 Issue #10, see: http://code.google.com/p/urllib3/issues/detail?id=1011 """12 13-import httplib13+try:14+ from http.client import HTTPSConnection15+except ImportError:16+ from httplib import HTTPSConnection17 from logging import getLogger18 from ntlm import ntlm19 20 from urllib3 import HTTPSConnectionPool34 unmodified lines55 headers['Connection'] = 'Keep-Alive'56 req_header = 'Authorization'57 resp_header = 'www-authenticate'58 56- conn = httplib.HTTPSConnection(host=self.host, port=self.port)59+ conn = HTTPSConnection(host=self.host, port=self.port)60 61 # Send negotiation message62 headers[req_header] = (63 'NTLM %s' % ntlm.create_NTLM_NEGOTIATE_MESSAGE(self.rawuser))57 unmodified linesmodified:requests/packages/urllib3/__init__.py+2 added-2 removed
1 # urllib3/__init__.py2-# Copyright 2008-2011 Andrey Petrov and contributors (see CONTRIBUTORS.txt)2+# Copyright 2008-2012 Andrey Petrov and contributors (see CONTRIBUTORS.txt)3 #4 # This module is part of urllib3 and is released under5 # the MIT License: http://www.opensource.org/licenses/mit-license.php6 2 unmodified lines9 """10 11 __author__ = 'Andrey Petrov (andrey.petrov@shazow.net)'12 __license__ = 'MIT'13-__version__ = '1.0.2'13+__version__ = '1.1'14 15 16 from .connectionpool import (17 HTTPConnectionPool,31 unmodified linesmodified:requests/packages/urllib3/_collections.py+1 added-1 removed
1 # urllib3/_collections.py2-# Copyright 2008-2011 Andrey Petrov and contributors (see CONTRIBUTORS.txt)2+# Copyright 2008-2012 Andrey Petrov and contributors (see CONTRIBUTORS.txt)3 #4 # This module is part of urllib3 and is released under5 # the MIT License: http://www.opensource.org/licenses/mit-license.php6 125 unmodified linesmodified:requests/packages/urllib3/connectionpool.py+21 added-9 removed
1 # urllib3/connectionpool.py2-# Copyright 2008-2011 Andrey Petrov and contributors (see CONTRIBUTORS.txt)2+# Copyright 2008-2012 Andrey Petrov and contributors (see CONTRIBUTORS.txt)3 #4 # This module is part of urllib3 and is released under5 # the MIT License: http://www.opensource.org/licenses/mit-license.php6 7 import logging8 import socket9 10+try: # Python 311+ from http.client import HTTPConnection, HTTPSConnection, HTTPException12+except ImportError:13+ from httplib import HTTPConnection, HTTPSConnection, HTTPException14 11-from httplib import HTTPConnection, HTTPSConnection, HTTPException12-from Queue import Queue, Empty, Full15+try: # Python 316+ from queue import Queue, Empty, Full17+except ImportError:18+ from Queue import Queue, Empty, Full19+ 20 from select import select21 from socket import error as SocketError, timeout as SocketTimeout22 23 from .packages.ssl_match_hostname import match_hostname, CertificateError15 unmodified lines39 HostChangedError,40 EmptyPoolError,41 )42 43+from . import six44+xrange = six.moves.xrange45 46+47 log = logging.getLogger(__name__)48 49 _Default = object()50 309 unmodified lines360 # The connection will be put back into the pool when361 # ``response.release_conn()`` is called (implicitly by362 # ``response.read()``)363 354- except (Empty), e:364+ except Empty as e:365 # Timed out by queue366 raise TimeoutError("Request timed out. (pool_timeout=%s)" %367 pool_timeout)368 359- except (SocketTimeout), e:369+ except SocketTimeout as e:370 # Timed out by socket371 raise TimeoutError("Request timed out. (timeout=%s)" %372 timeout)373 364- except (BaseSSLError), e:374+ except BaseSSLError as e:375 # SSL certificate error376 raise SSLError(e)377 368- except (CertificateError), e:378+ except CertificateError as e:379 # Name mismatch380 raise SSLError(e)381 372- except (HTTPException, SocketError), e:382+ except (HTTPException, SocketError) as e:383 # Connection broken, discard. It will be replaced next _get_conn().384 conn = None385+ # This is necessary so we can access e below386+ err = e387 388 finally:389 if conn and release_conn:390 # Put the connection back to be reused391 self._put_conn(conn)392 393 if not conn:394 log.warn("Retrying (%d attempts remain) after connection "383- "broken by '%r': %s" % (retries, e, url))395+ "broken by '%r': %s" % (retries, err, url))396 return self.urlopen(method, url, body, headers, retries - 1,397 redirect, assert_same_host) # Try again398 399 # Handle redirect?161 unmodified linesmodified:requests/packages/urllib3/exceptions.py+1 added-1 removed
1 # urllib3/exceptions.py2-# Copyright 2008-2011 Andrey Petrov and contributors (see CONTRIBUTORS.txt)2+# Copyright 2008-2012 Andrey Petrov and contributors (see CONTRIBUTORS.txt)3 #4 # This module is part of urllib3 and is released under5 # the MIT License: http://www.opensource.org/licenses/mit-license.php6 39 unmodified linesmodified:requests/packages/urllib3/filepost.py+19 added-15 removed
1 # urllib3/filepost.py2-# Copyright 2008-2011 Andrey Petrov and contributors (see CONTRIBUTORS.txt)2+# Copyright 2008-2012 Andrey Petrov and contributors (see CONTRIBUTORS.txt)3 #4 # This module is part of urllib3 and is released under5 # the MIT License: http://www.opensource.org/licenses/mit-license.php6 7 import codecs8-import mimetools8 import mimetypes9 10 try:12- from cStringIO import StringIO11+ from mimetools import choose_boundary12 except ImportError:14- from StringIO import StringIO # pylint: disable-msg=W040413+ # I don't like using an undocumented function, but I don't yet know what it does14+ from email.generator import _make_boundary as choose_boundary15 16+from io import BytesIO17 18+from . import six19+from .six import b20+21 writer = codecs.lookup('utf-8')[3]22 23 24 def get_content_type(filename):13 unmodified lines38 :param boundary:39 If not specified, then a random boundary will be generated using40 :func:`mimetools.choose_boundary`.41 """38- body = StringIO()42+ body = BytesIO()43 if boundary is None:40- boundary = mimetools.choose_boundary()44+ boundary = choose_boundary()45 42- for fieldname, value in fields.iteritems():43- body.write('--%s\r\n' % (boundary))46+ for fieldname, value in six.iteritems(fields):47+ body.write(b('--%s\r\n' % (boundary)))48 49 if isinstance(value, tuple):50 filename, data = value51 writer(body).write('Content-Disposition: form-data; name="%s"; '52 'filename="%s"\r\n' % (fieldname, filename))49- body.write('Content-Type: %s\r\n\r\n' %50- (get_content_type(filename)))53+ body.write(b('Content-Type: %s\r\n\r\n' %54+ (get_content_type(filename))))55 else:56 data = value57 writer(body).write('Content-Disposition: form-data; name="%s"\r\n'58 % (fieldname))55- body.write('Content-Type: text/plain\r\n\r\n')59+ body.write(b'Content-Type: text/plain\r\n\r\n')60 61 if isinstance(data, int):62 data = str(data) # Backwards compatibility63 60- if isinstance(data, unicode):64+ if isinstance(data, six.text_type):65 writer(body).write(data)66 else:67 body.write(data)68 65- body.write('\r\n')69+ body.write(b'\r\n')70 67- body.write('--%s--\r\n' % (boundary))71+ body.write(b('--%s--\r\n' % (boundary)))72 69- content_type = 'multipart/form-data; boundary=%s' % boundary73+ content_type = b('multipart/form-data; boundary=%s' % boundary)74 75 return body.getvalue(), content_typemodified:requests/packages/urllib3/poolmanager.py+2 added-2 removed
1 # urllib3/poolmanager.py2-# Copyright 2008-2011 Andrey Petrov and contributors (see CONTRIBUTORS.txt)2+# Copyright 2008-2012 Andrey Petrov and contributors (see CONTRIBUTORS.txt)3 #4 # This module is part of urllib3 and is released under5 # the MIT License: http://www.opensource.org/licenses/mit-license.php6 100 unmodified lines107 conn = self.connection_from_url(url)108 try:109 return conn.urlopen(method, url, **kw)110 111- except HostChangedError, e:111+ except HostChangedError as e:112 kw['retries'] = e.retries # Persist retries countdown113 return self.urlopen(method, e.new_url, **kw)114 115 18 unmodified linesmodified:requests/packages/urllib3/request.py+5 added-3 removed
1 # urllib3/request.py2-# Copyright 2008-2011 Andrey Petrov and contributors (see CONTRIBUTORS.txt)2+# Copyright 2008-2012 Andrey Petrov and contributors (see CONTRIBUTORS.txt)3 #4 # This module is part of urllib3 and is released under5 # the MIT License: http://www.opensource.org/licenses/mit-license.php6 7+try:8+ from urllib.parse import urlencode9+except ImportError:10+ from urllib import urlencode11 8-from urllib import urlencode9-12 from .filepost import encode_multipart_formdata13 14 15 __all__ = ['RequestMethods']132 unmodified linesmodified:requests/packages/urllib3/response.py+8 added-9 removed
1 # urllib3/response.py2-# Copyright 2008-2011 Andrey Petrov and contributors (see CONTRIBUTORS.txt)2+# Copyright 2008-2012 Andrey Petrov and contributors (see CONTRIBUTORS.txt)3 #4 # This module is part of urllib3 and is released under5 # the MIT License: http://www.opensource.org/licenses/mit-license.php6 7 import gzip8 import logging9 import zlib10 11+from io import BytesIO12 12-try:13- from cStringIO import StringIO14-except ImportError:15- from StringIO import StringIO # pylint: disable-msg=W040413 17-14 from .exceptions import HTTPError15 16 17 log = logging.getLogger(__name__)18 19 20 def decode_gzip(data):25- gzipper = gzip.GzipFile(fileobj=StringIO(data))21+ gzipper = gzip.GzipFile(fileobj=BytesIO(data))22 return gzipper.read()23 24 25 def decode_deflate(data):147 unmodified lines173 Remaining parameters are passed to the HTTPResponse constructor, along174 with ``original_response=r``.175 """176 177+ # HTTPResponse objects in Python 3 don't have a .strict attribute178+ strict = getattr(r, 'strict', 0)179 return ResponseCls(body=r,180+ # In Python 3, the header keys are returned capitalised182- headers=dict(r.getheaders()),181+ headers=dict((k.lower(), v) for k,v in r.getheaders()),182 status=r.status,183 version=r.version,184 reason=r.reason,186- strict=r.strict,185+ strict=strict,186 original_response=r,187 **response_kw)188 189 # Backwards-compatibility methods for httplib.HTTPResponse5 unmodified linesadded:requests/packages/urllib3/six.py+372 added
1+"""Utilities for writing code that runs on Python 2 and 3"""2+3+#Copyright (c) 2010-2011 Benjamin Peterson4+5+#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: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, 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.21+22+import operator23+import sys24+import types25+26+__author__ = "Benjamin Peterson <benjamin@python.org>"27+__version__ = "1.1.0"28+29+30+# True if we are running on Python 3.31+PY3 = sys.version_info[0] == 332+33+if PY3:34+ string_types = str,35+ integer_types = int,36+ class_types = type,37+ text_type = str38+ binary_type = bytes39+40+ MAXSIZE = sys.maxsize41+else:42+ string_types = basestring,43+ integer_types = (int, long)44+ class_types = (type, types.ClassType)45+ text_type = unicode46+ binary_type = str47+48+ # It's possible to have sizeof(long) != sizeof(Py_ssize_t).49+ class X(object):50+ def __len__(self):51+ return 1 << 3152+ try:53+ len(X())54+ except OverflowError:55+ # 32-bit56+ MAXSIZE = int((1 << 31) - 1)57+ else:58+ # 64-bit59+ MAXSIZE = int((1 << 63) - 1)60+ del X61+62+63+def _add_doc(func, doc):64+ """Add documentation to a function."""65+ func.__doc__ = doc66+67+68+def _import_module(name):69+ """Import module, returning the module after the last dot."""70+ __import__(name)71+ return sys.modules[name]72+73+74+class _LazyDescr(object):75+76+ def __init__(self, name):77+ self.name = name78+79+ def __get__(self, obj, tp):80+ result = self._resolve()81+ setattr(obj, self.name, result)82+ # This is a bit ugly, but it avoids running this again.83+ delattr(tp, self.name)84+ return result85+86+87+class MovedModule(_LazyDescr):88+89+ def __init__(self, name, old, new=None):90+ super(MovedModule, self).__init__(name)91+ if PY3:92+ if new is None:93+ new = name94+ self.mod = new95+ else:96+ self.mod = old97+98+ def _resolve(self):99+ return _import_module(self.mod)100+101+102+class MovedAttribute(_LazyDescr):103+104+ def __init__(self, name, old_mod, new_mod, old_attr=None, new_attr=None):105+ super(MovedAttribute, self).__init__(name)106+ if PY3:107+ if new_mod is None:108+ new_mod = name109+ self.mod = new_mod110+ if new_attr is None:111+ if old_attr is None:112+ new_attr = name113+ else:114+ new_attr = old_attr115+ self.attr = new_attr116+ else:117+ self.mod = old_mod118+ if old_attr is None:119+ old_attr = name120+ self.attr = old_attr121+122+ def _resolve(self):123+ module = _import_module(self.mod)124+ return getattr(module, self.attr)125+126+127+128+class _MovedItems(types.ModuleType):129+ """Lazy loading of moved objects"""130+131+132+_moved_attributes = [133+ MovedAttribute("cStringIO", "cStringIO", "io", "StringIO"),134+ MovedAttribute("filter", "itertools", "builtins", "ifilter", "filter"),135+ MovedAttribute("map", "itertools", "builtins", "imap", "map"),136+ MovedAttribute("reload_module", "__builtin__", "imp", "reload"),137+ MovedAttribute("reduce", "__builtin__", "functools"),138+ MovedAttribute("StringIO", "StringIO", "io"),139+ MovedAttribute("xrange", "__builtin__", "builtins", "xrange", "range"),140+ MovedAttribute("zip", "itertools", "builtins", "izip", "zip"),141+142+ MovedModule("builtins", "__builtin__"),143+ MovedModule("configparser", "ConfigParser"),144+ MovedModule("copyreg", "copy_reg"),145+ MovedModule("http_cookiejar", "cookielib", "http.cookiejar"),146+ MovedModule("http_cookies", "Cookie", "http.cookies"),147+ MovedModule("html_entities", "htmlentitydefs", "html.entities"),148+ MovedModule("html_parser", "HTMLParser", "html.parser"),149+ MovedModule("http_client", "httplib", "http.client"),150+ MovedModule("BaseHTTPServer", "BaseHTTPServer", "http.server"),151+ MovedModule("CGIHTTPServer", "CGIHTTPServer", "http.server"),152+ MovedModule("SimpleHTTPServer", "SimpleHTTPServer", "http.server"),153+ MovedModule("cPickle", "cPickle", "pickle"),154+ MovedModule("queue", "Queue"),155+ MovedModule("reprlib", "repr"),156+ MovedModule("socketserver", "SocketServer"),157+ MovedModule("tkinter", "Tkinter"),158+ MovedModule("tkinter_dialog", "Dialog", "tkinter.dialog"),159+ MovedModule("tkinter_filedialog", "FileDialog", "tkinter.filedialog"),160+ MovedModule("tkinter_scrolledtext", "ScrolledText", "tkinter.scrolledtext"),161+ MovedModule("tkinter_simpledialog", "SimpleDialog", "tkinter.simpledialog"),162+ MovedModule("tkinter_tix", "Tix", "tkinter.tix"),163+ MovedModule("tkinter_constants", "Tkconstants", "tkinter.constants"),164+ MovedModule("tkinter_dnd", "Tkdnd", "tkinter.dnd"),165+ MovedModule("tkinter_colorchooser", "tkColorChooser",166+ "tkinter.colorchooser"),167+ MovedModule("tkinter_commondialog", "tkCommonDialog",168+ "tkinter.commondialog"),169+ MovedModule("tkinter_tkfiledialog", "tkFileDialog", "tkinter.filedialog"),170+ MovedModule("tkinter_font", "tkFont", "tkinter.font"),171+ MovedModule("tkinter_messagebox", "tkMessageBox", "tkinter.messagebox"),172+ MovedModule("tkinter_tksimpledialog", "tkSimpleDialog",173+ "tkinter.simpledialog"),174+ MovedModule("urllib_robotparser", "robotparser", "urllib.robotparser"),175+ MovedModule("winreg", "_winreg"),176+]177+for attr in _moved_attributes:178+ setattr(_MovedItems, attr.name, attr)179+del attr180+181+moves = sys.modules["six.moves"] = _MovedItems("moves")182+183+184+def add_move(move):185+ """Add an item to six.moves."""186+ setattr(_MovedItems, move.name, move)187+188+189+def remove_move(name):190+ """Remove item from six.moves."""191+ try:192+ delattr(_MovedItems, name)193+ except AttributeError:194+ try:195+ del moves.__dict__[name]196+ except KeyError:197+ raise AttributeError("no such move, %r" % (name,))198+199+200+if PY3:201+ _meth_func = "__func__"202+ _meth_self = "__self__"203+204+ _func_code = "__code__"205+ _func_defaults = "__defaults__"206+207+ _iterkeys = "keys"208+ _itervalues = "values"209+ _iteritems = "items"210+else:211+ _meth_func = "im_func"212+ _meth_self = "im_self"213+214+ _func_code = "func_code"215+ _func_defaults = "func_defaults"216+217+ _iterkeys = "iterkeys"218+ _itervalues = "itervalues"219+ _iteritems = "iteritems"220+221+222+if PY3:223+ def get_unbound_function(unbound):224+ return unbound225+226+227+ advance_iterator = next228+229+ def callable(obj):230+ return any("__call__" in klass.__dict__ for klass in type(obj).__mro__)231+else:232+ def get_unbound_function(unbound):233+ return unbound.im_func234+235+236+ def advance_iterator(it):237+ return it.next()238+239+ callable = callable240+_add_doc(get_unbound_function,241+ """Get the function out of a possibly unbound function""")242+243+244+get_method_function = operator.attrgetter(_meth_func)245+get_method_self = operator.attrgetter(_meth_self)246+get_function_code = operator.attrgetter(_func_code)247+get_function_defaults = operator.attrgetter(_func_defaults)248+249+250+def iterkeys(d):251+ """Return an iterator over the keys of a dictionary."""252+ return getattr(d, _iterkeys)()253+254+def itervalues(d):255+ """Return an iterator over the values of a dictionary."""256+ return getattr(d, _itervalues)()257+258+def iteritems(d):259+ """Return an iterator over the (key, value) pairs of a dictionary."""260+ return getattr(d, _iteritems)()261+262+263+if PY3:264+ def b(s):265+ return s.encode("latin-1")266+ def u(s):267+ return s268+ if sys.version_info[1] <= 1:269+ def int2byte(i):270+ return bytes((i,))271+ else:272+ # This is about 2x faster than the implementation above on 3.2+273+ int2byte = operator.methodcaller("to_bytes", 1, "big")274+ import io275+ StringIO = io.StringIO276+ BytesIO = io.BytesIO277+else:278+ def b(s):279+ return s280+ def u(s):281+ return unicode(s, "unicode_escape")282+ int2byte = chr283+ import StringIO284+ StringIO = BytesIO = StringIO.StringIO285+_add_doc(b, """Byte literal""")286+_add_doc(u, """Text literal""")287+288+289+if PY3:290+ import builtins291+ exec_ = getattr(builtins, "exec")292+293+294+ def reraise(tp, value, tb=None):295+ if value.__traceback__ is not tb:296+ raise value.with_traceback(tb)297+ raise value298+299+300+ print_ = getattr(builtins, "print")301+ del builtins302+303+else:304+ def exec_(code, globs=None, locs=None):305+ """Execute code in a namespace."""306+ if globs is None:307+ frame = sys._getframe(1)308+ globs = frame.f_globals309+ if locs is None:310+ locs = frame.f_locals311+ del frame312+ elif locs is None:313+ locs = globs314+ exec("""exec code in globs, locs""")315+316+317+ exec_("""def reraise(tp, value, tb=None):318+ raise tp, value, tb319+""")320+321+322+ def print_(*args, **kwargs):323+ """The new-style print function."""324+ fp = kwargs.pop("file", sys.stdout)325+ if fp is None:326+ return327+ def write(data):328+ if not isinstance(data, basestring):329+ data = str(data)330+ fp.write(data)331+ want_unicode = False332+ sep = kwargs.pop("sep", None)333+ if sep is not None:334+ if isinstance(sep, unicode):335+ want_unicode = True336+ elif not isinstance(sep, str):337+ raise TypeError("sep must be None or a string")338+ end = kwargs.pop("end", None)339+ if end is not None:340+ if isinstance(end, unicode):341+ want_unicode = True342+ elif not isinstance(end, str):343+ raise TypeError("end must be None or a string")344+ if kwargs:345+ raise TypeError("invalid keyword arguments to print()")346+ if not want_unicode:347+ for arg in args:348+ if isinstance(arg, unicode):349+ want_unicode = True350+ break351+ if want_unicode:352+ newline = unicode("\n")353+ space = unicode(" ")354+ else:355+ newline = "\n"356+ space = " "357+ if sep is None:358+ sep = space359+ if end is None:360+ end = newline361+ for i, arg in enumerate(args):362+ if i:363+ write(sep)364+ write(arg)365+ write(end)366+367+_add_doc(reraise, """Reraise an exception.""")368+369+370+def with_metaclass(meta, base=object):371+ """Create a base class with a metaclass."""372+ return meta("NewBase", (base,), {})