Skip to content
Myr

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

10 files+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 lines
910Issue #10, see: http://code.google.com/p/urllib3/issues/detail?id=1011"""1213import httplib13try:14 from http.client import HTTPSConnection15except ImportError:16 from httplib import HTTPSConnection17from logging import getLogger18from ntlm import ntlm1920from urllib3 import HTTPSConnectionPool
34 unmodified lines
55 headers['Connection'] = 'Keep-Alive'56 req_header = 'Authorization'57 resp_header = 'www-authenticate'5856 conn = httplib.HTTPSConnection(host=self.host, port=self.port)59 conn = HTTPSConnection(host=self.host, port=self.port)6061 # Send negotiation message62 headers[req_header] = (63 'NTLM %s' % ntlm.create_NTLM_NEGOTIATE_MESSAGE(self.rawuser))
57 unmodified lines
modified: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 lines
9"""1011__author__ = 'Andrey Petrov (andrey.petrov@shazow.net)'12__license__ = 'MIT'13__version__ = '1.0.2'13__version__ = '1.1'141516from .connectionpool import (17 HTTPConnectionPool,
31 unmodified lines
modified: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 lines
modified: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.php67import logging8import socket910try: # Python 311 from http.client import HTTPConnection, HTTPSConnection, HTTPException12except ImportError:13 from httplib import HTTPConnection, HTTPSConnection, HTTPException1411from httplib import HTTPConnection, HTTPSConnection, HTTPException12from Queue import Queue, Empty, Full15try: # Python 316 from queue import Queue, Empty, Full17except ImportError:18 from Queue import Queue, Empty, Full19 20from select import select21from socket import error as SocketError, timeout as SocketTimeout2223from .packages.ssl_match_hostname import match_hostname, CertificateError
15 unmodified lines
39 HostChangedError,40 EmptyPoolError,41)4243from . import six44xrange = six.moves.xrange454647log = logging.getLogger(__name__)4849_Default = object()50
309 unmodified lines
360 # The connection will be put back into the pool when361 # ``response.release_conn()`` is called (implicitly by362 # ``response.read()``)363354 except (Empty), e:364 except Empty as e:365 # Timed out by queue366 raise TimeoutError("Request timed out. (pool_timeout=%s)" %367 pool_timeout)368359 except (SocketTimeout), e:369 except SocketTimeout as e:370 # Timed out by socket371 raise TimeoutError("Request timed out. (timeout=%s)" %372 timeout)373364 except (BaseSSLError), e:374 except BaseSSLError as e:375 # SSL certificate error376 raise SSLError(e)377368 except (CertificateError), e:378 except CertificateError as e:379 # Name mismatch380 raise SSLError(e)381372 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 = e387388 finally:389 if conn and release_conn:390 # Put the connection back to be reused391 self._put_conn(conn)392393 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 again398399 # Handle redirect?
161 unmodified lines
modified: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 lines
modified: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.php67import codecs8import mimetools8import mimetypes910try:12 from cStringIO import StringIO11 from mimetools import choose_boundary12except 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_boundary1516from io import BytesIO1718from . import six19from .six import b2021writer = codecs.lookup('utf-8')[3]222324def get_content_type(filename):
13 unmodified lines
38 :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()4542 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)))4849 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')6061 if isinstance(data, int):62 data = str(data) # Backwards compatibility6360 if isinstance(data, unicode):64 if isinstance(data, six.text_type):65 writer(body).write(data)66 else:67 body.write(data)6865 body.write('\r\n')69 body.write(b'\r\n')7067 body.write('--%s--\r\n' % (boundary))71 body.write(b('--%s--\r\n' % (boundary)))7269 content_type = 'multipart/form-data; boundary=%s' % boundary73 content_type = b('multipart/form-data; boundary=%s' % boundary)7475 return body.getvalue(), content_type
modified: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 lines
107 conn = self.connection_from_url(url)108 try:109 return conn.urlopen(method, url, **kw)110111 except HostChangedError, e:111 except HostChangedError as e:112 kw['retries'] = e.retries # Persist retries countdown113 return self.urlopen(method, e.new_url, **kw)114115
18 unmodified lines
modified: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.php67try:8 from urllib.parse import urlencode9except ImportError:10 from urllib import urlencode118from urllib import urlencode912from .filepost import encode_multipart_formdata131415__all__ = ['RequestMethods']
132 unmodified lines
modified: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.php67import gzip8import logging9import zlib1011from io import BytesIO1212try:13 from cStringIO import StringIO14except ImportError:15 from StringIO import StringIO # pylint: disable-msg=W0404131714from .exceptions import HTTPError151617log = logging.getLogger(__name__)181920def decode_gzip(data):25 gzipper = gzip.GzipFile(fileobj=StringIO(data))21 gzipper = gzip.GzipFile(fileobj=BytesIO(data))22 return gzipper.read()232425def decode_deflate(data):
147 unmodified lines
173 Remaining parameters are passed to the HTTPResponse constructor, along174 with ``original_response=r``.175 """176177 # 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)188189 # Backwards-compatibility methods for httplib.HTTPResponse
5 unmodified lines
added:requests/packages/urllib3/six.py+372 added
1"""Utilities for writing code that runs on Python 2 and 3"""23#Copyright (c) 2010-2011 Benjamin Peterson45#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:1112#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.2122import operator23import sys24import types2526__author__ = "Benjamin Peterson <benjamin@python.org>"27__version__ = "1.1.0"282930# True if we are running on Python 3.31PY3 = sys.version_info[0] == 33233if PY3:34 string_types = str,35 integer_types = int,36 class_types = type,37 text_type = str38 binary_type = bytes3940 MAXSIZE = sys.maxsize41else:42 string_types = basestring,43 integer_types = (int, long)44 class_types = (type, types.ClassType)45 text_type = unicode46 binary_type = str4748 # 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 X616263def _add_doc(func, doc):64 """Add documentation to a function."""65 func.__doc__ = doc666768def _import_module(name):69 """Import module, returning the module after the last dot."""70 __import__(name)71 return sys.modules[name]727374class _LazyDescr(object):7576 def __init__(self, name):77 self.name = name7879 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 result858687class MovedModule(_LazyDescr):8889 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 = old9798 def _resolve(self):99 return _import_module(self.mod)100101102class MovedAttribute(_LazyDescr):103104 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_attr121122 def _resolve(self):123 module = _import_module(self.mod)124 return getattr(module, self.attr)125126127128class _MovedItems(types.ModuleType):129 """Lazy loading of moved objects"""130131132_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"),141142 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]177for attr in _moved_attributes:178 setattr(_MovedItems, attr.name, attr)179del attr180181moves = sys.modules["six.moves"] = _MovedItems("moves")182183184def add_move(move):185 """Add an item to six.moves."""186 setattr(_MovedItems, move.name, move)187188189def 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,))198199200if PY3:201 _meth_func = "__func__"202 _meth_self = "__self__"203204 _func_code = "__code__"205 _func_defaults = "__defaults__"206207 _iterkeys = "keys"208 _itervalues = "values"209 _iteritems = "items"210else:211 _meth_func = "im_func"212 _meth_self = "im_self"213214 _func_code = "func_code"215 _func_defaults = "func_defaults"216217 _iterkeys = "iterkeys"218 _itervalues = "itervalues"219 _iteritems = "iteritems"220221222if PY3:223 def get_unbound_function(unbound):224 return unbound225226227 advance_iterator = next228229 def callable(obj):230 return any("__call__" in klass.__dict__ for klass in type(obj).__mro__)231else:232 def get_unbound_function(unbound):233 return unbound.im_func234235236 def advance_iterator(it):237 return it.next()238239 callable = callable240_add_doc(get_unbound_function,241 """Get the function out of a possibly unbound function""")242243244get_method_function = operator.attrgetter(_meth_func)245get_method_self = operator.attrgetter(_meth_self)246get_function_code = operator.attrgetter(_func_code)247get_function_defaults = operator.attrgetter(_func_defaults)248249250def iterkeys(d):251 """Return an iterator over the keys of a dictionary."""252 return getattr(d, _iterkeys)()253254def itervalues(d):255 """Return an iterator over the values of a dictionary."""256 return getattr(d, _itervalues)()257258def iteritems(d):259 """Return an iterator over the (key, value) pairs of a dictionary."""260 return getattr(d, _iteritems)()261262263if 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.BytesIO277else: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""")287288289if PY3:290 import builtins291 exec_ = getattr(builtins, "exec")292293294 def reraise(tp, value, tb=None):295 if value.__traceback__ is not tb:296 raise value.with_traceback(tb)297 raise value298299300 print_ = getattr(builtins, "print")301 del builtins302303else: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""")315316317 exec_("""def reraise(tp, value, tb=None):318 raise tp, value, tb319""")320321322 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)366367_add_doc(reraise, """Reraise an exception.""")368369370def with_metaclass(meta, base=object):371 """Create a base class with a metaclass."""372 return meta("NewBase", (base,), {})