Skip to content
Myr

update internal dependencies

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 db108a1 · Browse files · 9 files+247 added−163 removed
This commit

State

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

Diff stats

9 files+247 added−163 removed

  • other:+247 added−163 removed

9 files+247 added−163 removed

modified:requests/packages/charade/__init__.py+34 added
28 unmodified lines
29 u.reset()30 u.feed(aBuf)31 u.close()32 return u.result3334def _description_of(path):35 """Return a string describing the probable encoding of a file."""36 from charade.universaldetector import UniversalDetector3738 u = UniversalDetector()39 for line in open(path, 'rb'):40 u.feed(line)41 u.close()42 result = u.result43 if result['encoding']:44 return '%s: %s with confidence %s' % (path,45 result['encoding'],46 result['confidence'])47 else:48 return '%s: no result' % path495051def charade_cli():52 """53 Script which takes one or more file paths and reports on their detected54 encodings5556 Example::5758 % chardetect.py somefile someotherfile59 somefile: windows-1252 with confidence 0.560 someotherfile: ascii with confidence 1.06162 """63 from sys import argv64 for path in argv[1:]:65 print(_description_of(path))66
added:requests/packages/charade/__main__.py+7 added
1'''2support ';python -m charade <file1> [file2] ...' package execution syntax (2.7+)3'''45from charade import charade_cli67charade_cli()
modified:requests/packages/charade/jpcntx.py+1 added-1 removed
167 unmodified lines
168169 def get_confidence(self):170 # This is just one way to calculate confidence. It works well for me.171 if self._mTotalRel > MINIMUM_DATA_THRESHOLD:172 return (self._mTotalRel - self._mRelSample[0]) / self._mTotalRel172 return float(self._mTotalRel - self._mRelSample[0]) / self._mTotalRel173 else:174 return DONT_KNOW175176 def get_order(self, aBuf):
43 unmodified lines
modified:requests/packages/charade/latin1prober.py+1 added-1 removed
127 unmodified lines
128 total = sum(self._mFreqCounter)129 if total < 0.01:130 confidence = 0.0131 else:132 confidence = ((self._mFreqCounter[3] / total)132 confidence = ((float(self._mFreqCounter[3]) / total)133 - (self._mFreqCounter[1] * 20.0 / total))134 if confidence < 0.0:135 confidence = 0.0136 # lower the confidence of latin1 so that other more accurate
3 unmodified lines
modified:requests/packages/charade/universaldetector.py+4 added-8 removed
72 unmodified lines
73 # If the data starts with BOM, we know it is UTF74 if aBuf[:3] == codecs.BOM:75 # EF BB BF UTF-8 with BOM76 self.result = {'encoding': "UTF-8", 'confidence': 1.0}77 elif aBuf[:4] == codecs.BOM_UTF32_LE:77 elif aBuf[:4] in (codecs.BOM_UTF32_LE, codecs.BOM_UTF32_BE):78 # FF FE 00 00 UTF-32, little-endian BOM79 self.result = {'encoding': "UTF-32LE", 'confidence': 1.0}80 elif aBuf[:4] == codecs.BOM_UTF32_BE:79 # 00 00 FE FF UTF-32, big-endian BOM82 self.result = {'encoding': "UTF-32BE", 'confidence': 1.0}80 self.result = {'encoding': "UTF-32", 'confidence': 1.0}81 elif aBuf[:4] == b'\xFE\xFF\x00\x00':82 # FE FF 00 00 UCS-4, unusual octet order BOM (3412)83 self.result = {84 'encoding': "X-ISO-10646-UCS-4-3412",
4 unmodified lines
89 self.result = {90 'encoding': "X-ISO-10646-UCS-4-2143",91 'confidence': 1.092 }95 elif aBuf[:2] == codecs.BOM_LE:93 elif aBuf[:2] == codecs.BOM_LE or aBuf[:2] == codecs.BOM_BE:94 # FF FE UTF-16, little endian BOM97 self.result = {'encoding': "UTF-16LE", 'confidence': 1.0}98 elif aBuf[:2] == codecs.BOM_BE:95 # FE FF UTF-16, big endian BOM100 self.result = {'encoding': "UTF-16BE", 'confidence': 1.0}96 self.result = {'encoding': "UTF-16", 'confidence': 1.0}9798 self._mGotData = True99 if self.result['encoding'] and (self.result['confidence'] > 0.0):100 self.done = True
68 unmodified lines
modified:requests/packages/urllib3/contrib/pyopenssl.py+2 added
24 unmodified lines
25import OpenSSL.SSL26from pyasn1.codec.der import decoder as der_decoder27from socket import _fileobject28import ssl29import select30from cStringIO import StringIO3132from .. import connectionpool33from .. import util
302 unmodified lines
336 while True:337 try:338 cnx.do_handshake()339 except OpenSSL.SSL.WantReadError:340 select.select([sock], [], [])341 continue342 except OpenSSL.SSL.Error as e:343 raise ssl.SSLError('bad handshake', e)344 break
2 unmodified lines
added:requests/packages/urllib3/connection.py+107 added
1# urllib3/connection.py2# Copyright 2008-2013 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 socket8from socket import timeout as SocketTimeout910try: # Python 311 from http.client import HTTPConnection, HTTPException12except ImportError:13 from httplib import HTTPConnection, HTTPException1415class DummyConnection(object):16 "Used to detect a failed ConnectionCls import."17 pass1819try: # Compiled with SSL?20 ssl = None21 HTTPSConnection = DummyConnection2223 class BaseSSLError(BaseException):24 pass2526 try: # Python 327 from http.client import HTTPSConnection28 except ImportError:29 from httplib import HTTPSConnection3031 import ssl32 BaseSSLError = ssl.SSLError3334except (ImportError, AttributeError): # Platform-specific: No SSL.35 pass3637from .exceptions import (38 ConnectTimeoutError,39)40from .packages.ssl_match_hostname import match_hostname41from .util import (42 assert_fingerprint,43 resolve_cert_reqs,44 resolve_ssl_version,45 ssl_wrap_socket,46)4748class VerifiedHTTPSConnection(HTTPSConnection):49 """50 Based on httplib.HTTPSConnection but wraps the socket with51 SSL certification.52 """53 cert_reqs = None54 ca_certs = None55 ssl_version = None5657 def set_cert(self, key_file=None, cert_file=None,58 cert_reqs=None, ca_certs=None,59 assert_hostname=None, assert_fingerprint=None):6061 self.key_file = key_file62 self.cert_file = cert_file63 self.cert_reqs = cert_reqs64 self.ca_certs = ca_certs65 self.assert_hostname = assert_hostname66 self.assert_fingerprint = assert_fingerprint6768 def connect(self):69 # Add certificate verification70 try:71 sock = socket.create_connection(72 address=(self.host, self.port),73 timeout=self.timeout,74 )75 except SocketTimeout:76 raise ConnectTimeoutError(77 self, "Connection to %s timed out. (connect timeout=%s)" %78 (self.host, self.timeout))7980 resolved_cert_reqs = resolve_cert_reqs(self.cert_reqs)81 resolved_ssl_version = resolve_ssl_version(self.ssl_version)8283 if self._tunnel_host:84 self.sock = sock85 # Calls self._set_hostport(), so self.host is86 # self._tunnel_host below.87 self._tunnel()8889 # Wrap socket using verification with the root certs in90 # trusted_root_certs91 self.sock = ssl_wrap_socket(sock, self.key_file, self.cert_file,92 cert_reqs=resolved_cert_reqs,93 ca_certs=self.ca_certs,94 server_hostname=self.host,95 ssl_version=resolved_ssl_version)9697 if resolved_cert_reqs != ssl.CERT_NONE:98 if self.assert_fingerprint:99 assert_fingerprint(self.sock.getpeercert(binary_form=True),100 self.assert_fingerprint)101 elif self.assert_hostname is not False:102 match_hostname(self.sock.getpeercert(),103 self.assert_hostname or self.host)104105106if ssl:107 HTTPSConnection = VerifiedHTTPSConnection
modified:requests/packages/urllib3/connectionpool.py+67 added-138 removed
9 unmodified lines
10from socket import error as SocketError, timeout as SocketTimeout11import socket1213try: # Python 314 from http.client import HTTPConnection, HTTPException15 from http.client import HTTP_PORT, HTTPS_PORT16except ImportError:17 from httplib import HTTPConnection, HTTPException18 from httplib import HTTP_PORT, HTTPS_PORT1920try: # Python 314 from queue import LifoQueue, Empty, Full15except ImportError:16 from Queue import LifoQueue, Empty, Full17 import Queue as _ # Platform-specific: Windows181927try: # Compiled with SSL?28 HTTPSConnection = object2930 class BaseSSLError(BaseException):31 pass3233 ssl = None3435 try: # Python 336 from http.client import HTTPSConnection37 except ImportError:38 from httplib import HTTPSConnection3940 import ssl41 BaseSSLError = ssl.SSLError4243except (ImportError, AttributeError): # Platform-specific: No SSL.44 pass454620from .exceptions import (21 ClosedPoolError,22 ConnectTimeoutError,23 EmptyPoolError,24 HostChangedError,25 MaxRetryError,26 SSLError,27 TimeoutError,28 ReadTimeoutError,29 ProxyError,30)57from .packages.ssl_match_hostname import CertificateError, match_hostname31from .packages.ssl_match_hostname import CertificateError32from .packages import six33from .connection import (34 DummyConnection,35 HTTPConnection, HTTPSConnection, VerifiedHTTPSConnection,36 HTTPException, BaseSSLError,37)38from .request import RequestMethods39from .response import HTTPResponse40from .util import (41 assert_fingerprint,42 get_host,43 is_connection_dropped,65 resolve_cert_reqs,66 resolve_ssl_version,67 ssl_wrap_socket,44 Timeout,45)464748xrange = six.moves.xrange4950log = logging.getLogger(__name__)5152_Default = object()5354port_by_scheme = {78 'http': HTTP_PORT,79 'https': HTTPS_PORT,55 'http': 80,56 'https': 443,57}585983## Connection objects (extension of httplib)8485class VerifiedHTTPSConnection(HTTPSConnection):86 """87 Based on httplib.HTTPSConnection but wraps the socket with88 SSL certification.89 """90 cert_reqs = None91 ca_certs = None92 ssl_version = None9394 def set_cert(self, key_file=None, cert_file=None,95 cert_reqs=None, ca_certs=None,96 assert_hostname=None, assert_fingerprint=None):9798 self.key_file = key_file99 self.cert_file = cert_file100 self.cert_reqs = cert_reqs101 self.ca_certs = ca_certs102 self.assert_hostname = assert_hostname103 self.assert_fingerprint = assert_fingerprint104105 def connect(self):106 # Add certificate verification107 try:108 sock = socket.create_connection(109 address=(self.host, self.port),110 timeout=self.timeout)111 except SocketTimeout:112 raise ConnectTimeoutError(113 self, "Connection to %s timed out. (connect timeout=%s)" %114 (self.host, self.timeout))115116 resolved_cert_reqs = resolve_cert_reqs(self.cert_reqs)117 resolved_ssl_version = resolve_ssl_version(self.ssl_version)118119 if self._tunnel_host:120 self.sock = sock121 # Calls self._set_hostport(), so self.host is122 # self._tunnel_host below.123 self._tunnel()124125 # Wrap socket using verification with the root certs in126 # trusted_root_certs127 self.sock = ssl_wrap_socket(sock, self.key_file, self.cert_file,128 cert_reqs=resolved_cert_reqs,129 ca_certs=self.ca_certs,130 server_hostname=self.host,131 ssl_version=resolved_ssl_version)132133 if resolved_cert_reqs != ssl.CERT_NONE:134 if self.assert_fingerprint:135 assert_fingerprint(self.sock.getpeercert(binary_form=True),136 self.assert_fingerprint)137 elif self.assert_hostname is not False:138 match_hostname(self.sock.getpeercert(),139 self.assert_hostname or self.host)14014160## Pool objects6162class ConnectionPool(object):63 """
71 unmodified lines
135 instead, see :class:`urllib3.connectionpool.ProxyManager`"136 """137138 scheme = 'http'139 ConnectionCls = HTTPConnection140141 def __init__(self, host, port=None, strict=False,142 timeout=Timeout.DEFAULT_TIMEOUT, maxsize=1, block=False,143 headers=None, _proxy=None, _proxy_headers=None):
29 unmodified lines
173 """174 self.num_connections += 1175 log.info("Starting new HTTP connection (%d): %s" %176 (self.num_connections, self.host))177178 extra_params = {}179 if not six.PY3: # Python 2180 extra_params['strict'] = self.strict181262 return HTTPConnection(host=self.host, port=self.port,263 timeout=self.timeout.connect_timeout,264 **extra_params)182 return self.ConnectionCls(host=self.host, port=self.port,183 timeout=self.timeout.connect_timeout,184 **extra_params)185266186 def _get_conn(self, timeout=None):187 """188 Get a connection. Will return a pooled connection if one is available.189
90 unmodified lines
280 try:281 timeout_obj.start_connect()282 conn.timeout = timeout_obj.connect_timeout283 # conn.request() calls httplib.*.request, not the method in365 # request.py. It also calls makefile (recv) on the socket284 # urllib3.request. It also calls makefile (recv) on the socket.285 conn.request(method, url, **httplib_request_kw)286 except SocketTimeout:287 raise ConnectTimeoutError(288 self, "Connection to %s timed out. (connect timeout=%s)" %289 (self.host, timeout_obj.connect_timeout))290291 # Reset the timeout for the recv() on the socket292 read_timeout = timeout_obj.read_timeout374 log.debug("Setting read timeout to %s" % read_timeout)293294 # App Engine doesn't have a sock attr376 if hasattr(conn, 'sock') and \377 read_timeout is not None and \378 read_timeout is not Timeout.DEFAULT_TIMEOUT:295 if hasattr(conn, 'sock'):296 # In Python 3 socket.py will catch EAGAIN and return None when you297 # try and read into the file pointer created by http.client, which298 # instead raises a BadStatusLine exception. Instead of catching299 # the exception and assuming all BadStatusLine exceptions are read
1 unmodified line
301 if read_timeout == 0:302 raise ReadTimeoutError(303 self, url,304 "Read timed out. (read timeout=%s)" % read_timeout)305 if read_timeout is Timeout.DEFAULT_TIMEOUT:306 conn.sock.settimeout(socket.getdefaulttimeout())307 else: # None or a value388 conn.sock.settimeout(read_timeout)308 conn.sock.settimeout(read_timeout)309310 # Receive the response from the server311 try:312 try: # Python 2.7+, use buffering of HTTP responses
3 unmodified lines
316 except SocketTimeout:317 raise ReadTimeoutError(318 self, url, "Read timed out. (read timeout=%s)" % read_timeout)319320 except BaseSSLError as e:321 # Catch possible read timeouts thrown as SSL errors. If not the322 # case, rethrow the original. We need to do this because of:323 # http://bugs.python.org/issue10272324 if 'timed out' in str(e) or \325 'did not complete (read)' in str(e): # Python 2.6326 raise ReadTimeoutError(self, url, "Read timed out.")327328 raise329330 except SocketError as e: # Platform-specific: Python 2331 # See the above comment about EAGAIN in Python 3. In Python 2 we332 # have to specifically catch it and throw the timeout error333 if e.errno in _blocking_errnos:334 raise ReadTimeoutError(335 self, url,336 "Read timed out. (read timeout=%s)" % read_timeout)337338 raise339409340 # AppEngine doesn't have a version attr.341 http_version = getattr(conn, '_http_vsn_str', 'HTTP/?')342 log.debug("\"%s %s %s\" %s %s" % (method, url, http_version,343 httplib_response.status,
144 unmodified lines
488 # ``response.read()``)489490 except Empty:491 # Timed out by queue562 raise ReadTimeoutError(563 self, url, "Read timed out, no pool connections are available.")492 raise EmptyPoolError(self, "No pool connections are available.")493565 except SocketTimeout:566 # Timed out by socket567 raise ReadTimeoutError(self, url, "Read timed out.")568494 except BaseSSLError as e:570 # SSL certificate error571 if 'timed out' in str(e) or \572 'did not complete (read)' in str(e): # Platform-specific: Python 2.6573 raise ReadTimeoutError(self, url, "Read timed out.")495 raise SSLError(e)496497 except CertificateError as e:498 # Name mismatch499 raise SSLError(e)500501 except TimeoutError as e:502 # Connection broken, discard.503 conn = None504 # Save the error off for retry logic.505 err = e506507 if retries == 0:508 raise509510 except (HTTPException, SocketError) as e:511 if isinstance(e, SocketError) and self.proxy is not None:512 raise ProxyError('Cannot connect to proxy. '513 'Socket error: %s.' % e)
54 unmodified lines
568 into an SSL socket.569 """570571 scheme = 'https'572 ConnectionCls = HTTPSConnection573574 def __init__(self, host, port=None,575 strict=False, timeout=None, maxsize=1,576 block=False, headers=None,
11 unmodified lines
588 self.ssl_version = ssl_version589 self.assert_hostname = assert_hostname590 self.assert_fingerprint = assert_fingerprint591661 def _prepare_conn(self, connection):592 def _prepare_conn(self, conn):593 """594 Prepare the ``connection`` for :meth:`urllib3.util.ssl_wrap_socket`595 and establish the tunnel if proxy is used.596 """597667 if isinstance(connection, VerifiedHTTPSConnection):668 connection.set_cert(key_file=self.key_file,669 cert_file=self.cert_file,670 cert_reqs=self.cert_reqs,671 ca_certs=self.ca_certs,672 assert_hostname=self.assert_hostname,673 assert_fingerprint=self.assert_fingerprint)674 connection.ssl_version = self.ssl_version598 if isinstance(conn, VerifiedHTTPSConnection):599 conn.set_cert(key_file=self.key_file,600 cert_file=self.cert_file,601 cert_reqs=self.cert_reqs,602 ca_certs=self.ca_certs,603 assert_hostname=self.assert_hostname,604 assert_fingerprint=self.assert_fingerprint)605 conn.ssl_version = self.ssl_version606607 if self.proxy is not None:608 # Python 2.7+609 try:679 set_tunnel = connection.set_tunnel610 set_tunnel = conn.set_tunnel611 except AttributeError: # Platform-specific: Python 2.6681 set_tunnel = connection._set_tunnel612 set_tunnel = conn._set_tunnel613 set_tunnel(self.host, self.port, self.proxy_headers)614 # Establish tunnel connection early, because otherwise httplib615 # would improperly set Host: header to proxy's IP:port.685 connection.connect()616 conn.connect()617687 return connection618 return conn619620 def _new_conn(self):621 """622 Return a fresh :class:`httplib.HTTPSConnection`.
1 unmodified line
624 self.num_connections += 1625 log.info("Starting new HTTPS connection (%d): %s"626 % (self.num_connections, self.host))627628 if not self.ConnectionCls or self.ConnectionCls is DummyConnection:629 # Platform-specific: Python without ssl630 raise SSLError("Can't connect to HTTPS URL because the SSL "631 "module is not available.")632633 actual_host = self.host634 actual_port = self.port635 if self.proxy is not None:636 actual_host = self.proxy.host637 actual_port = self.proxy.port638703 if not ssl: # Platform-specific: Python compiled without +ssl704 if not HTTPSConnection or HTTPSConnection is object:705 raise SSLError("Can't connect to HTTPS URL because the SSL "706 "module is not available.")707 connection_class = HTTPSConnection708 else:709 connection_class = VerifiedHTTPSConnection710639 extra_params = {}640 if not six.PY3: # Python 2641 extra_params['strict'] = self.strict714 connection = connection_class(host=actual_host, port=actual_port,715 timeout=self.timeout.connect_timeout,716 **extra_params)642718 return self._prepare_conn(connection)643 conn = self.ConnectionCls(host=actual_host, port=actual_port,644 timeout=self.timeout.connect_timeout,645 **extra_params)646647 return self._prepare_conn(conn)648649650def connection_from_url(url, **kw):651 """652 Given a url, return an :class:`.ConnectionPool` instance of its host.653
21 unmodified lines
modified:requests/packages/urllib3/util.py+24 added-15 removed
78 unmodified lines
7980 :type read: integer, float, or None8182 :param total:83 The maximum amount of time to wait for an HTTP request to connect and84 return. This combines the connect and read timeouts into one. In the83 This combines the connect and read timeouts into one; the read timeout84 will be set to the time leftover from the connect attempt. In the85 event that both a connect timeout and a total are specified, or a read86 timeout and a total are specified, the shorter timeout will be applied.8788 Defaults to None.899090 :type total: integer, float, or None9192 .. note::93
5 unmodified lines
99 urllib3 to return a response may be greater than the value passed to100 `total`.101102 In addition, the read and total timeouts only measure the time between104 read operations on the socket connecting the client and the server, not105 the total amount of time for the request to return a complete response.106 As an example, you may want a request to return within 7 seconds or107 fail, so you set the ``total`` timeout to 7 seconds. If the server108 sends one byte to you every 5 seconds, the request will **not** trigger109 time out. This case is admittedly rare.103 read operations on the socket connecting the client and the server,104 not the total amount of time for the request to return a complete105 response. For most requests, the timeout is raised because the server106 has not sent the first byte in the specified time. This is not always107 the case; if a server streams one byte every fifteen seconds, a timeout108 of 20 seconds will not ever trigger, even though the request will109 take several minutes to complete.110111 If your goal is to cut off any request after a set amount of wall clock112 time, consider having a second "watcher" thread to cut off a slow113 request.114 """115116 #: A sentinel object representing the default timeout value117 DEFAULT_TIMEOUT = _GLOBAL_DEFAULT_TIMEOUT118115 def __init__(self, connect=_Default, read=_Default, total=None):119 def __init__(self, total=None, connect=_Default, read=_Default):120 self._connect = self._validate_timeout(connect, 'connect')121 self._read = self._validate_timeout(read, 'read')122 self.total = self._validate_timeout(total, 'total')123 self._start_connect = None
251 unmodified lines
375 path = delim + path_376377 # Auth378 if '@' in url:379 # Last '@' denotes end of auth part375 auth, url = url.split('@', 1)380 auth, url = url.rsplit('@', 1)381382 # IPv6383 if url and url[0] == '[':384 host, url = url.split(']', 1)
5 unmodified lines
390391 if not host:392 host = _host393394 if port:395 # If given, ports must be integers.389 if not port.isdigit():390 raise LocationParseError("Failed to parse: %s" % url)396 if not port.isdigit():397 raise LocationParseError("Failed to parse: %s" % url)398 port = int(port)399 else:400 # Blank ports are cool, too. (rfc3986#section-3.2.3)401 port = None402392 port = int(port)393403 elif not host and url:404 host = url405406 if not path:
229 unmodified lines