new 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 e7598e0 · Browse files · 8 files·+190 added−72 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
8 files+190 added−72 removed
- other:+190 added−72 removed
Provenance
- Commit
2c5b020- Tree
8de417f- Author
Kenneth Reitz <me@kennethreitz.com>- Committer
Kenneth Reitz <me@kennethreitz.com>- Parent
e7598e0
8 files changed+190 added−72 removed
modified:requests/packages/urllib3/packages/six.py+33 added-20 removed
22 unmodified lines23 import sys24 import types25 26 __author__ = "Benjamin Peterson <benjamin@python.org>"27-__version__ = "1.1.0"27+__version__ = "1.2.0" # Revision 41c74fef2ded28 29 30 # True if we are running on Python 3.31 PY3 = sys.version_info[0] == 312 unmodified lines44 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-bit48+ if sys.platform.startswith("java"):49+ # Jython always uses 32 bits.50 MAXSIZE = int((1 << 31) - 1)51 else:52+ # It's possible to have sizeof(long) != sizeof(Py_ssize_t).53+ class X(object):54+ def __len__(self):55+ return 1 << 3156+ try:57+ len(X())58+ except OverflowError:59+ # 32-bit60+ MAXSIZE = int((1 << 31) - 1)61+ else:58- # 64-bit59- MAXSIZE = int((1 << 63) - 1)60- del X62+ # 64-bit63+ MAXSIZE = int((1 << 63) - 1)64+ del X65 66 67 def _add_doc(func, doc):68 """Add documentation to a function."""66 unmodified lines135 136 _moved_attributes = [137 MovedAttribute("cStringIO", "cStringIO", "io", "StringIO"),138 MovedAttribute("filter", "itertools", "builtins", "ifilter", "filter"),139+ MovedAttribute("input", "__builtin__", "builtins", "raw_input", "input"),140 MovedAttribute("map", "itertools", "builtins", "imap", "map"),141 MovedAttribute("reload_module", "__builtin__", "imp", "reload"),142 MovedAttribute("reduce", "__builtin__", "functools"),143 MovedAttribute("StringIO", "StringIO", "io"),38 unmodified lines182 for attr in _moved_attributes:183 setattr(_MovedItems, attr.name, attr)184 del attr185 181-moves = sys.modules["six.moves"] = _MovedItems("moves")186+moves = sys.modules[__name__ + ".moves"] = _MovedItems("moves")187 188 189 def add_move(move):190 """Add an item to six.moves."""32 unmodified lines223 _itervalues = "itervalues"224 _iteritems = "iteritems"225 226 227+try:228+ advance_iterator = next229+except NameError:230+ def advance_iterator(it):231+ return it.next()232+next = advance_iterator233+234+235 if PY3:236 def get_unbound_function(unbound):237 return unbound238 239+ Iterator = object240 227- advance_iterator = next228-241 def callable(obj):242 return any("__call__" in klass.__dict__ for klass in type(obj).__mro__)243 else:244 def get_unbound_function(unbound):245 return unbound.im_func246 247+ class Iterator(object):248 236- def advance_iterator(it):237- return it.next()249+ def next(self):250+ return type(self).__next__(self)251 252 callable = callable253 _add_doc(get_unbound_function,254 """Get the function out of a possibly unbound function""")6 unmodified lines261 262 263 def iterkeys(d):264 """Return an iterator over the keys of a dictionary."""252- return getattr(d, _iterkeys)()265+ return iter(getattr(d, _iterkeys)())266 267 def itervalues(d):268 """Return an iterator over the values of a dictionary."""256- return getattr(d, _itervalues)()269+ return iter(getattr(d, _itervalues)())270 271 def iteritems(d):272 """Return an iterator over the (key, value) pairs of a dictionary."""260- return getattr(d, _iteritems)()273+ return iter(getattr(d, _iteritems)())274 275 276 if PY3:277 def b(s):108 unmodified linesmodified:requests/packages/urllib3/connectionpool.py+38 added-17 removed
4 unmodified lines5 # the MIT License: http://www.opensource.org/licenses/mit-license.php6 7 import logging8 import socket9+import errno10 10-from socket import timeout as SocketTimeout11+from socket import error as SocketError, timeout as SocketTimeout12 13 try: # Python 314 from http.client import HTTPConnection, HTTPException15 from http.client import HTTP_PORT, HTTPS_PORT25 unmodified lines41 42 43 from .request import RequestMethods44 from .response import HTTPResponse44-from .util import get_host, is_connection_dropped45+from .util import get_host, is_connection_dropped, ssl_wrap_socket46 from .exceptions import (47 ClosedPoolError,48 EmptyPoolError,49 HostChangedError,26 unmodified lines76 SSL certification.77 """78 cert_reqs = None79 ca_certs = None80+ ssl_version = None81 82 def set_cert(self, key_file=None, cert_file=None,83 cert_reqs='CERT_NONE', ca_certs=None):84 ssl_req_scheme = {12 unmodified lines97 sock = socket.create_connection((self.host, self.port), self.timeout)98 99 # Wrap socket using verification with the root certs in100 # trusted_root_certs99- self.sock = ssl.wrap_socket(sock, self.key_file, self.cert_file,101+ self.sock = ssl_wrap_socket(sock, self.key_file, self.cert_file,102 cert_reqs=self.cert_reqs,101- ca_certs=self.ca_certs)103+ ca_certs=self.ca_certs,104+ server_hostname=self.host,105+ ssl_version=self.ssl_version)106+107 if self.ca_certs:108 match_hostname(self.sock.getpeercert(), self.host)109 110 59 unmodified lines170 scheme = 'http'171 172 def __init__(self, host, port=None, strict=False, timeout=None, maxsize=1,173 block=False, headers=None):169- super(HTTPConnectionPool, self).__init__(host, port)174+ ConnectionPool.__init__(self, host, port)175+ RequestMethods.__init__(self, headers)176 177 self.strict = strict178 self.timeout = timeout179 self.pool = self.QueueCls(maxsize)180 self.block = block175- self.headers = headers or {}181 182 # Fill the queue up so that doing get() on it will block properly183 for _ in xrange(maxsize):184 self.pool.put(None)8 unmodified lines193 """194 self.num_connections += 1195 log.info("Starting new HTTP connection (%d): %s" %196 (self.num_connections, self.host))192- return HTTPConnection(host=self.host, port=self.port)197+ return HTTPConnection(host=self.host,198+ port=self.port,199+ strict=self.strict)200 201 def _get_conn(self, timeout=None):202 """203 Get a connection. Will return a pooled connection if one is available.251 unmodified lines455 except CertificateError as e:456 # Name mismatch457 raise SSLError(e)458 452- except HTTPException as e:459+ except (HTTPException, SocketError) as e:460 # Connection broken, discard. It will be replaced next _get_conn().461 conn = None462 # This is necessary so we can access e below463 err = e464 465+ if retries == 0:466+ raise MaxRetryError(self, url, e)467+468 finally:469 if release_conn:470 # Put the connection back to be reused. If the connection is471 # expired then it will be None, which will get replaced with a28 unmodified lines500 Same as :class:`.HTTPConnectionPool`, but HTTPS.501 502 When Python is compiled with the :mod:`ssl` module, then503 :class:`.VerifiedHTTPSConnection` is used, which *can* verify certificates,494- instead of :class:httplib.HTTPSConnection`.504+ instead of :class:`httplib.HTTPSConnection`.505 496- The ``key_file``, ``cert_file``, ``cert_reqs``, and ``ca_certs`` parameters506+ The ``key_file``, ``cert_file``, ``cert_reqs``, ``ca_certs``, and ``ssl_version``507 are only used if :mod:`ssl` is available and are fed into498- :meth:`ssl.wrap_socket` to upgrade the connection socket into an SSL socket.508+ :meth:`urllib3.util.ssl_wrap_socket` to upgrade the connection socket into an SSL socket.509 """510 511 scheme = 'https'512 513 def __init__(self, host, port=None,514 strict=False, timeout=None, maxsize=1,515 block=False, headers=None,516 key_file=None, cert_file=None,507- cert_reqs='CERT_NONE', ca_certs=None):517+ cert_reqs='CERT_NONE', ca_certs=None, ssl_version=None):518 509- super(HTTPSConnectionPool, self).__init__(host, port,510- strict, timeout, maxsize,511- block, headers)519+ HTTPConnectionPool.__init__(self, host, port,520+ strict, timeout, maxsize,521+ block, headers)522 self.key_file = key_file523 self.cert_file = cert_file524 self.cert_reqs = cert_reqs525 self.ca_certs = ca_certs526+ self.ssl_version = ssl_version527 528 def _new_conn(self):529 """530 Return a fresh :class:`httplib.HTTPSConnection`.6 unmodified lines537 if not HTTPSConnection or HTTPSConnection is object:538 raise SSLError("Can't connect to HTTPS URL because the SSL "539 "module is not available.")540 530- return HTTPSConnection(host=self.host, port=self.port)541+ return HTTPSConnection(host=self.host,542+ port=self.port,543+ strict=self.strict)544 532- connection = VerifiedHTTPSConnection(host=self.host, port=self.port)545+ connection = VerifiedHTTPSConnection(host=self.host,546+ port=self.port,547+ strict=self.strict)548 connection.set_cert(key_file=self.key_file, cert_file=self.cert_file,549 cert_reqs=self.cert_reqs, ca_certs=self.ca_certs)550+551+ if self.ssl_version is None:552+ connection.ssl_version = ssl.PROTOCOL_SSLv23553+ else:554+ connection.ssl_version = self.ssl_version555+556 return connection557 558 559 def connection_from_url(url, **kw):24 unmodified linesmodified:requests/packages/urllib3/exceptions.py+13 added-3 removed
16 unmodified lines17 def __init__(self, pool, message):18 self.pool = pool19 HTTPError.__init__(self, "%s: %s" % (pool, message))20 21+ def __reduce__(self):22+ # For pickling purposes.23+ return self.__class__, (None, self.url)24 25+26 class SSLError(HTTPError):27 "Raised when SSL certificate fails in an HTTPS connection."28 pass29 7 unmodified lines37 38 class MaxRetryError(PoolError):39 "Raised when the maximum number of retries is exceeded."40 37- def __init__(self, pool, url):41+ def __init__(self, pool, url, reason=None):42+ self.reason = reason43+44 message = "Max retries exceeded with url: %s" % url39- PoolError.__init__(self, pool, message)45+ if reason:46+ message += " (Caused by %s: %s)" % (type(reason), reason)47+ else:48+ message += " (Caused by redirect)"49 50+ PoolError.__init__(self, pool, message)51 self.url = url52 53 54 class HostChangedError(PoolError):26 unmodified lines81 "Raised when get_host or similar fails to parse the URL input."82 83 def __init__(self, location):84 message = "Failed to parse: %s" % location75- super(LocationParseError, self).__init__(self, message)85+ HTTPError.__init__(self, message)86 87 self.location = locationmodified:requests/packages/urllib3/filepost.py+15 added-8 removed
39 unmodified lines40 41 42 def encode_multipart_formdata(fields, boundary=None):43 """44- Encode a dictionary of ``fields`` using the multipart/form-data mime format.44+ Encode a dictionary of ``fields`` using the multipart/form-data MIME format.45 46 :param fields:47- Dictionary of fields or list of (key, value) field tuples. The key is48- treated as the field name, and the value as the body of the form-data49- bytes. If the value is a tuple of two elements, then the first element50- is treated as the filename of the form-data section.47+ Dictionary of fields or list of (key, value) or (key, value, MIME type)48+ field tuples. The key is treated as the field name, and the value as49+ the body of the form-data bytes. If the value is a tuple of two50+ elements, then the first element is treated as the filename of the51+ form-data section and a suitable MIME type is guessed based on the52+ filename. If the value is a tuple of three elements, then the third53+ element is treated as an explicit MIME type of the form-data section.54 55 Field names and filenames must be unicode.56 57 :param boundary:7 unmodified lines65 for fieldname, value in iter_fields(fields):66 body.write(b('--%s\r\n' % (boundary)))67 68 if isinstance(value, tuple):69+ if len(value) == 3:70+ filename, data, content_type = value71+ else:66- filename, data = value72+ filename, data = value73+ content_type = get_content_type(filename)74 writer(body).write('Content-Disposition: form-data; name="%s"; '75 'filename="%s"\r\n' % (fieldname, filename))76 body.write(b('Content-Type: %s\r\n\r\n' %70- (get_content_type(filename))))77+ (content_type,)))78 else:79 data = value80 writer(body).write('Content-Disposition: form-data; name="%s"\r\n'81 % (fieldname))75- body.write(b'Content-Type: text/plain\r\n\r\n')82+ body.write(b'\r\n')83 84 if isinstance(data, int):85 data = str(data) # Backwards compatibility86 12 unmodified linesmodified:requests/packages/urllib3/poolmanager.py+18 added-13 removed
28 unmodified lines29 Allows for arbitrary requests while transparently keeping track of30 necessary connection pools for you.31 32 :param num_pools:33- Number of connection pools to cache before discarding the least recently34- used pool.33+ Number of connection pools to cache before discarding the least34+ recently used pool.35 36+ :param headers:37+ Headers to include with all requests, unless other headers are given38+ explicitly.39+40 :param \**connection_pool_kw:41 Additional parameters are used to create fresh42 :class:`urllib3.connectionpool.ConnectionPool` instances.43 44 Example: ::45 46 >>> manager = PoolManager(num_pools=2)43- >>> r = manager.urlopen("http://google.com/")44- >>> r = manager.urlopen("http://google.com/mail")45- >>> r = manager.urlopen("http://yahoo.com/")47+ >>> r = manager.request('GET', 'http://google.com/')48+ >>> r = manager.request('GET', 'http://google.com/mail')49+ >>> r = manager.request('GET', 'http://yahoo.com/')50 >>> len(manager.pools)51 252 53 """54 51- def __init__(self, num_pools=10, **connection_pool_kw):55+ def __init__(self, num_pools=10, headers=None, **connection_pool_kw):56+ RequestMethods.__init__(self, headers)57 self.connection_pool_kw = connection_pool_kw58 self.pools = RecentlyUsedContainer(num_pools,59 dispose_func=lambda p: p.close())60 56 unmodified lines117 conn = self.connection_from_host(u.host, port=u.port, scheme=u.scheme)118 119 kw['assert_same_host'] = False120 kw['redirect'] = False121+ if 'headers' not in kw:122+ kw['headers'] = self.headers123 124 response = conn.urlopen(method, u.request_uri, **kw)125 126 redirect_location = redirect and response.get_redirect_location()3 unmodified lines130 if response.status == 303:131 method = 'GET'132 133 log.info("Redirecting %s -> %s" % (url, redirect_location))127- kw['retries'] = kw.get('retries', 3) - 1 # Persist retries countdown134+ kw['retries'] = kw.get('retries', 3) - 1 # Persist retries countdown135 return self.urlopen(method, redirect_location, **kw)136 137 138 class ProxyManager(RequestMethods):5 unmodified lines144 def __init__(self, proxy_pool):145 self.proxy_pool = proxy_pool146 147 def _set_proxy_headers(self, headers=None):141- headers = headers or {}148+ headers_ = {'Accept': '*/*'}149+ if headers:150+ headers_.update(headers)151 143- # Same headers are curl passes for --proxy1.0144- headers['Accept'] = '*/*'145- headers['Proxy-Connection'] = 'Keep-Alive'152+ return headers_153 147- return headers148-154 def urlopen(self, method, url, **kw):155 "Same as HTTP(S)ConnectionPool.urlopen, ``url`` must be absolute."156 kw['assert_same_host'] = False157 kw['headers'] = self._set_proxy_headers(kw.get('headers'))6 unmodified linesmodified:requests/packages/urllib3/request.py+20 added-6 removed
34 unmodified lines35 36 :meth:`.request` is for making any kind of request, it will look up the37 appropriate encoding format and use one of the above two methods to make38 the request.39+40+ Initializer parameters:41+42+ :param headers:43+ Headers to include with all requests, unless other headers are given44+ explicitly.45 """46 47 _encode_url_methods = set(['DELETE', 'GET', 'HEAD', 'OPTIONS'])42-48 _encode_body_methods = set(['PATCH', 'POST', 'PUT', 'TRACE'])49 50+ def __init__(self, headers=None):51+ self.headers = headers or {}52+53 def urlopen(self, method, url, body=None, headers=None,54 encode_multipart=True, multipart_boundary=None,55 **kw): # Abstract56 raise NotImplemented("Classes extending RequestMethods must implement "47 unmodified lines104 safe to use it in other times too. However, it may break request signing,105 such as with OAuth.106 107 Supports an optional ``fields`` parameter of key/value strings AND100- key/filetuple. A filetuple is a (filename, data) tuple. For example: ::108+ key/filetuple. A filetuple is a (filename, data, MIME type) tuple where109+ the MIME type is optional. For example: ::110 111 fields = {112 'foo': 'bar',113 'fakefile': ('foofile.txt', 'contents of foofile'),114 'realfile': ('barfile.txt', open('realfile').read()),106- 'nonamefile': ('contents of nonamefile field'),115+ 'typedfile': ('bazfile.bin', open('bazfile').read(),116+ 'image/jpeg'),117+ 'nonamefile': 'contents of nonamefile field',118 }119 120 When uploading a file, providing a filename (the first parameter of the121 tuple) is optional but recommended to best mimick behavior of browsers.9 unmodified lines131 else:132 body, content_type = (urlencode(fields or {}),133 'application/x-www-form-urlencoded')134 124- headers = headers or {}125- headers.update({'Content-Type': content_type})135+ if headers is None:136+ headers = self.headers137 138+ headers_ = {'Content-Type': content_type}139+ headers_.update(headers)140+127- return self.urlopen(method, url, body=body, headers=headers,141+ return self.urlopen(method, url, body=body, headers=headers_,142 **urlopen_kw)modified:requests/packages/urllib3/response.py+3 added-1 removed
128 unmodified lines129 is useful if you want the ``.data`` property to continue working130 after having ``.read()`` the file object. (Overridden if ``amt`` is131 set.)132 """133+ # Note: content-encoding value should be case-insensitive, per RFC 2616134+ # Section 3.5133- content_encoding = self.headers.get('content-encoding')135+ content_encoding = self.headers.get('content-encoding', '').lower()136 decoder = self.CONTENT_DECODERS.get(content_encoding)137 if decode_content is None:138 decode_content = self._decode_content139 65 unmodified linesmodified:requests/packages/urllib3/util.py+50 added-4 removed
9 unmodified lines10 from socket import error as SocketError11 12 try:13 from select import poll, POLLIN14-except ImportError: # `poll` doesn't exist on OSX and other platforms14+except ImportError: # `poll` doesn't exist on OSX and other platforms15 poll = False16 try:17 from select import select18- except ImportError: # `select` doesn't exist on AppEngine.18+ except ImportError: # `select` doesn't exist on AppEngine.19 select = False20 21+try: # Test for SSL features22+ SSLContext = None23+ HAS_SNI = False24+25+ from ssl import wrap_socket, CERT_NONE, SSLError, PROTOCOL_SSLv2326+ from ssl import SSLContext # Modern SSL?27+ from ssl import HAS_SNI # Has SNI?28+except ImportError:29+ pass30+31+32 from .packages import six33 from .exceptions import LocationParseError34 35 66 unmodified lines102 Example: ::103 104 >>> parse_url('http://google.com/mail/')105 Url(scheme='http', host='google.com', port=None, path='/', ...)95- >>> prase_url('google.com:80')106+ >>> parse_url('google.com:80')107 Url(scheme=None, host='google.com', port=80, path=None, ...)97- >>> prase_url('/foo?bar')108+ >>> parse_url('/foo?bar')109 Url(scheme=None, host=None, port=None, path='/foo', query='bar', ...)110 """111 112 # While this code has overlap with stdlib's urlparse, it is much147 unmodified lines260 for (fno, ev) in p.poll(0.0):261 if fno == sock.fileno():262 # Either data is buffered (bad), or the connection is dropped.263 return True264+265+266+if SSLContext is not None: # Python 3.2+267+ def ssl_wrap_socket(sock, keyfile=None, certfile=None, cert_reqs=CERT_NONE,268+ ca_certs=None, server_hostname=None,269+ ssl_version=PROTOCOL_SSLv23):270+ """271+ All arguments except `server_hostname` have the same meaning as for272+ :func:`ssl.wrap_socket`273+274+ :param server_hostname:275+ Hostname of the expected certificate276+ """277+ context = SSLContext(ssl_version)278+ context.verify_mode = cert_reqs279+ if ca_certs:280+ try:281+ context.load_verify_locations(ca_certs)282+ except TypeError as e: # Reraise as SSLError283+ # FIXME: This block needs a test.284+ raise SSLError(e)285+ if certfile:286+ # FIXME: This block needs a test.287+ context.load_cert_chain(certfile, keyfile)288+ if HAS_SNI: # Platform-specific: OpenSSL with enabled SNI289+ return context.wrap_socket(sock, server_hostname=server_hostname)290+ return context.wrap_socket(sock)291+292+else: # Python 3.1 and earlier293+ def ssl_wrap_socket(sock, keyfile=None, certfile=None, cert_reqs=CERT_NONE,294+ ca_certs=None, server_hostname=None,295+ ssl_version=PROTOCOL_SSLv23):296+ return wrap_socket(sock, keyfile=keyfile, certfile=certfile,297+ ca_certs=ca_certs, cert_reqs=cert_reqs,298+ ssl_version=ssl_version)