Skip to content
Myr

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

8 files+190 added−72 removed

modified:requests/packages/urllib3/packages/six.py+33 added-20 removed
22 unmodified lines
23import sys24import types2526__author__ = "Benjamin Peterson <benjamin@python.org>"27__version__ = "1.1.0"27__version__ = "1.2.0" # Revision 41c74fef2ded282930# True if we are running on Python 3.31PY3 = sys.version_info[0] == 3
12 unmodified lines
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-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 X656667def _add_doc(func, doc):68 """Add documentation to a function."""
66 unmodified lines
135136_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 lines
182for attr in _moved_attributes:183 setattr(_MovedItems, attr.name, attr)184del attr185181moves = sys.modules["six.moves"] = _MovedItems("moves")186moves = sys.modules[__name__ + ".moves"] = _MovedItems("moves")187188189def add_move(move):190 """Add an item to six.moves."""
32 unmodified lines
223 _itervalues = "itervalues"224 _iteritems = "iteritems"225226227try:228 advance_iterator = next229except NameError:230 def advance_iterator(it):231 return it.next()232next = advance_iterator233234235if PY3:236 def get_unbound_function(unbound):237 return unbound238239 Iterator = object240227 advance_iterator = next228241 def callable(obj):242 return any("__call__" in klass.__dict__ for klass in type(obj).__mro__)243else:244 def get_unbound_function(unbound):245 return unbound.im_func246247 class Iterator(object):248236 def advance_iterator(it):237 return it.next()249 def next(self):250 return type(self).__next__(self)251252 callable = callable253_add_doc(get_unbound_function,254 """Get the function out of a possibly unbound function""")
6 unmodified lines
261262263def iterkeys(d):264 """Return an iterator over the keys of a dictionary."""252 return getattr(d, _iterkeys)()265 return iter(getattr(d, _iterkeys)())266267def itervalues(d):268 """Return an iterator over the values of a dictionary."""256 return getattr(d, _itervalues)()269 return iter(getattr(d, _itervalues)())270271def 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)())274275276if PY3:277 def b(s):
108 unmodified lines
modified:requests/packages/urllib3/connectionpool.py+38 added-17 removed
4 unmodified lines
5# the MIT License: http://www.opensource.org/licenses/mit-license.php67import logging8import socket9import errno1010from socket import timeout as SocketTimeout11from socket import error as SocketError, timeout as SocketTimeout1213try: # Python 314 from http.client import HTTPConnection, HTTPException15 from http.client import HTTP_PORT, HTTPS_PORT
25 unmodified lines
414243from .request import RequestMethods44from .response import HTTPResponse44from .util import get_host, is_connection_dropped45from .util import get_host, is_connection_dropped, ssl_wrap_socket46from .exceptions import (47 ClosedPoolError,48 EmptyPoolError,49 HostChangedError,
26 unmodified lines
76 SSL certification.77 """78 cert_reqs = None79 ca_certs = None80 ssl_version = None8182 def set_cert(self, key_file=None, cert_file=None,83 cert_reqs='CERT_NONE', ca_certs=None):84 ssl_req_scheme = {
12 unmodified lines
97 sock = socket.create_connection((self.host, self.port), self.timeout)9899 # 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)106107 if self.ca_certs:108 match_hostname(self.sock.getpeercert(), self.host)109110
59 unmodified lines
170 scheme = 'http'171172 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)176177 self.strict = strict178 self.timeout = timeout179 self.pool = self.QueueCls(maxsize)180 self.block = block175 self.headers = headers or {}181182 # Fill the queue up so that doing get() on it will block properly183 for _ in xrange(maxsize):184 self.pool.put(None)
8 unmodified lines
193 """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)200201 def _get_conn(self, timeout=None):202 """203 Get a connection. Will return a pooled connection if one is available.
251 unmodified lines
455 except CertificateError as e:456 # Name mismatch457 raise SSLError(e)458452 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 = e464465 if retries == 0:466 raise MaxRetryError(self, url, e)467468 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 a
28 unmodified lines
500 Same as :class:`.HTTPConnectionPool`, but HTTPS.501502 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`.505496 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 """510511 scheme = 'https'512513 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):518509 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_version527528 def _new_conn(self):529 """530 Return a fresh :class:`httplib.HTTPSConnection`.
6 unmodified lines
537 if not HTTPSConnection or HTTPSConnection is object:538 raise SSLError("Can't connect to HTTPS URL because the SSL "539 "module is not available.")540530 return HTTPSConnection(host=self.host, port=self.port)541 return HTTPSConnection(host=self.host,542 port=self.port,543 strict=self.strict)544532 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)550551 if self.ssl_version is None:552 connection.ssl_version = ssl.PROTOCOL_SSLv23553 else:554 connection.ssl_version = self.ssl_version555556 return connection557558559def connection_from_url(url, **kw):
24 unmodified lines
modified:requests/packages/urllib3/exceptions.py+13 added-3 removed
16 unmodified lines
17 def __init__(self, pool, message):18 self.pool = pool19 HTTPError.__init__(self, "%s: %s" % (pool, message))2021 def __reduce__(self):22 # For pickling purposes.23 return self.__class__, (None, self.url)242526class SSLError(HTTPError):27 "Raised when SSL certificate fails in an HTTPS connection."28 pass29
7 unmodified lines
3738class MaxRetryError(PoolError):39 "Raised when the maximum number of retries is exceeded."4037 def __init__(self, pool, url):41 def __init__(self, pool, url, reason=None):42 self.reason = reason4344 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)"4950 PoolError.__init__(self, pool, message)51 self.url = url525354class HostChangedError(PoolError):
26 unmodified lines
81 "Raised when get_host or similar fails to parse the URL input."8283 def __init__(self, location):84 message = "Failed to parse: %s" % location75 super(LocationParseError, self).__init__(self, message)85 HTTPError.__init__(self, message)8687 self.location = location
modified:requests/packages/urllib3/filepost.py+15 added-8 removed
39 unmodified lines
404142def 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.4546 :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.5455 Field names and filenames must be unicode.5657 :param boundary:
7 unmodified lines
65 for fieldname, value in iter_fields(fields):66 body.write(b('--%s\r\n' % (boundary)))6768 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')8384 if isinstance(data, int):85 data = str(data) # Backwards compatibility86
12 unmodified lines
modified:requests/packages/urllib3/poolmanager.py+18 added-13 removed
28 unmodified lines
29 Allows for arbitrary requests while transparently keeping track of30 necessary connection pools for you.3132 :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.3536 :param headers:37 Headers to include with all requests, unless other headers are given38 explicitly.3940 :param \**connection_pool_kw:41 Additional parameters are used to create fresh42 :class:`urllib3.connectionpool.ConnectionPool` instances.4344 Example: ::4546 >>> 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 25253 """5451 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 lines
117 conn = self.connection_from_host(u.host, port=u.port, scheme=u.scheme)118119 kw['assert_same_host'] = False120 kw['redirect'] = False121 if 'headers' not in kw:122 kw['headers'] = self.headers123124 response = conn.urlopen(method, u.request_uri, **kw)125126 redirect_location = redirect and response.get_redirect_location()
3 unmodified lines
130 if response.status == 303:131 method = 'GET'132133 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)136137138class ProxyManager(RequestMethods):
5 unmodified lines
144 def __init__(self, proxy_pool):145 self.proxy_pool = proxy_pool146147 def _set_proxy_headers(self, headers=None):141 headers = headers or {}148 headers_ = {'Accept': '*/*'}149 if headers:150 headers_.update(headers)151143 # Same headers are curl passes for --proxy1.0144 headers['Accept'] = '*/*'145 headers['Proxy-Connection'] = 'Keep-Alive'152 return headers_153147 return headers148154 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 lines
modified:requests/packages/urllib3/request.py+20 added-6 removed
34 unmodified lines
3536 :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.3940 Initializer parameters:4142 :param headers:43 Headers to include with all requests, unless other headers are given44 explicitly.45 """4647 _encode_url_methods = set(['DELETE', 'GET', 'HEAD', 'OPTIONS'])4248 _encode_body_methods = set(['PATCH', 'POST', 'PUT', 'TRACE'])4950 def __init__(self, headers=None):51 self.headers = headers or {}5253 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 lines
104 safe to use it in other times too. However, it may break request signing,105 such as with OAuth.106107 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: ::110111 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 }119120 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 lines
131 else:132 body, content_type = (urlencode(fields or {}),133 'application/x-www-form-urlencoded')134124 headers = headers or {}125 headers.update({'Content-Type': content_type})135 if headers is None:136 headers = self.headers137138 headers_ = {'Content-Type': content_type}139 headers_.update(headers)140127 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 lines
129 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 lines
modified:requests/packages/urllib3/util.py+50 added-4 removed
9 unmodified lines
10from socket import error as SocketError1112try:13 from select import poll, POLLIN14except ImportError: # `poll` doesn't exist on OSX and other platforms14except 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 = False2021try: # Test for SSL features22 SSLContext = None23 HAS_SNI = False2425 from ssl import wrap_socket, CERT_NONE, SSLError, PROTOCOL_SSLv2326 from ssl import SSLContext # Modern SSL?27 from ssl import HAS_SNI # Has SNI?28except ImportError:29 pass303132from .packages import six33from .exceptions import LocationParseError3435
66 unmodified lines
102 Example: ::103104 >>> 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 """111112 # While this code has overlap with stdlib's urlparse, it is much
147 unmodified lines
260 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 True264265266if 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`273274 :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)291292else: # 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)