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
Provenance
- Commit
df272b7- Tree
942552d- Author
Kenneth Reitz <me@kennethreitz.com>- Committer
Kenneth Reitz <me@kennethreitz.com>- Parent
db108a1
9 files changed+247 added−163 removed
modified:requests/packages/charade/__init__.py+34 added
28 unmodified lines29 u.reset()30 u.feed(aBuf)31 u.close()32 return u.result33+34+def _description_of(path):35+ """Return a string describing the probable encoding of a file."""36+ from charade.universaldetector import UniversalDetector37+38+ 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' % path49+50+51+def charade_cli():52+ """53+ Script which takes one or more file paths and reports on their detected54+ encodings55+56+ Example::57+58+ % chardetect.py somefile someotherfile59+ somefile: windows-1252 with confidence 0.560+ someotherfile: ascii with confidence 1.061+62+ """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+'''2+support ';python -m charade <file1> [file2] ...' package execution syntax (2.7+)3+'''4+5+from charade import charade_cli6+7+charade_cli()modified:requests/packages/charade/jpcntx.py+1 added-1 removed
167 unmodified lines168 169 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_KNOW175 176 def get_order(self, aBuf):43 unmodified linesmodified:requests/packages/charade/latin1prober.py+1 added-1 removed
127 unmodified lines128 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 accurate3 unmodified linesmodified:requests/packages/charade/universaldetector.py+4 added-8 removed
72 unmodified lines73 # 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 lines89 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}97 98 self._mGotData = True99 if self.result['encoding'] and (self.result['confidence'] > 0.0):100 self.done = True68 unmodified linesmodified:requests/packages/urllib3/contrib/pyopenssl.py+2 added
24 unmodified lines25 import OpenSSL.SSL26 from pyasn1.codec.der import decoder as der_decoder27 from socket import _fileobject28 import ssl29+import select30 from cStringIO import StringIO31 32 from .. import connectionpool33 from .. import util302 unmodified lines336 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 break2 unmodified linesadded: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.php6+7+import socket8+from socket import timeout as SocketTimeout9+10+try: # Python 311+ from http.client import HTTPConnection, HTTPException12+except ImportError:13+ from httplib import HTTPConnection, HTTPException14+15+class DummyConnection(object):16+ "Used to detect a failed ConnectionCls import."17+ pass18+19+try: # Compiled with SSL?20+ ssl = None21+ HTTPSConnection = DummyConnection22+23+ class BaseSSLError(BaseException):24+ pass25+26+ try: # Python 327+ from http.client import HTTPSConnection28+ except ImportError:29+ from httplib import HTTPSConnection30+31+ import ssl32+ BaseSSLError = ssl.SSLError33+34+except (ImportError, AttributeError): # Platform-specific: No SSL.35+ pass36+37+from .exceptions import (38+ ConnectTimeoutError,39+)40+from .packages.ssl_match_hostname import match_hostname41+from .util import (42+ assert_fingerprint,43+ resolve_cert_reqs,44+ resolve_ssl_version,45+ ssl_wrap_socket,46+)47+48+class 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 = None56+57+ def set_cert(self, key_file=None, cert_file=None,58+ cert_reqs=None, ca_certs=None,59+ assert_hostname=None, assert_fingerprint=None):60+61+ 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_fingerprint67+68+ 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))79+80+ resolved_cert_reqs = resolve_cert_reqs(self.cert_reqs)81+ resolved_ssl_version = resolve_ssl_version(self.ssl_version)82+83+ if self._tunnel_host:84+ self.sock = sock85+ # Calls self._set_hostport(), so self.host is86+ # self._tunnel_host below.87+ self._tunnel()88+89+ # 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)96+97+ 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)104+105+106+if ssl:107+ HTTPSConnection = VerifiedHTTPSConnectionmodified:requests/packages/urllib3/connectionpool.py+67 added-138 removed
9 unmodified lines10 from socket import error as SocketError, timeout as SocketTimeout11 import socket12 13 try: # Python 314- from http.client import HTTPConnection, HTTPException15- from http.client import HTTP_PORT, HTTPS_PORT16-except ImportError:17- from httplib import HTTPConnection, HTTPException18- from httplib import HTTP_PORT, HTTPS_PORT19-20-try: # Python 314 from queue import LifoQueue, Empty, Full15 except ImportError:16 from Queue import LifoQueue, Empty, Full17 import Queue as _ # Platform-specific: Windows18 19 27-try: # Compiled with SSL?28- HTTPSConnection = object29-30- class BaseSSLError(BaseException):31- pass32-33- ssl = None34-35- try: # Python 336- from http.client import HTTPSConnection37- except ImportError:38- from httplib import HTTPSConnection39-40- import ssl41- BaseSSLError = ssl.SSLError42-43-except (ImportError, AttributeError): # Platform-specific: No SSL.44- pass45-46-20 from .exceptions import (21 ClosedPoolError,22 ConnectTimeoutError,23 EmptyPoolError,24 HostChangedError,25 MaxRetryError,26 SSLError,27+ TimeoutError,28 ReadTimeoutError,29 ProxyError,30 )57-from .packages.ssl_match_hostname import CertificateError, match_hostname31+from .packages.ssl_match_hostname import CertificateError32 from .packages import six33+from .connection import (34+ DummyConnection,35+ HTTPConnection, HTTPSConnection, VerifiedHTTPSConnection,36+ HTTPException, BaseSSLError,37+)38 from .request import RequestMethods39 from .response import HTTPResponse40 from .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 )46 47+48 xrange = six.moves.xrange49 50 log = logging.getLogger(__name__)51 52 _Default = object()53 54 port_by_scheme = {78- 'http': HTTP_PORT,79- 'https': HTTPS_PORT,55+ 'http': 80,56+ 'https': 443,57 }58 59 83-## Connection objects (extension of httplib)84-85-class 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 = None93-94- def set_cert(self, key_file=None, cert_file=None,95- cert_reqs=None, ca_certs=None,96- assert_hostname=None, assert_fingerprint=None):97-98- 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_fingerprint104-105- 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))115-116- resolved_cert_reqs = resolve_cert_reqs(self.cert_reqs)117- resolved_ssl_version = resolve_ssl_version(self.ssl_version)118-119- if self._tunnel_host:120- self.sock = sock121- # Calls self._set_hostport(), so self.host is122- # self._tunnel_host below.123- self._tunnel()124-125- # 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)132-133- 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)140-141-60 ## Pool objects61 62 class ConnectionPool(object):63 """71 unmodified lines135 instead, see :class:`urllib3.connectionpool.ProxyManager`"136 """137 138 scheme = 'http'139+ ConnectionCls = HTTPConnection140 141 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 lines173 """174 self.num_connections += 1175 log.info("Starting new HTTP connection (%d): %s" %176 (self.num_connections, self.host))177+178 extra_params = {}179 if not six.PY3: # Python 2180 extra_params['strict'] = self.strict181 262- 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)185 266-186 def _get_conn(self, timeout=None):187 """188 Get a connection. Will return a pooled connection if one is available.189 90 unmodified lines280 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))290 291 # Reset the timeout for the recv() on the socket292 read_timeout = timeout_obj.read_timeout374- log.debug("Setting read timeout to %s" % read_timeout)293+294 # 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 read1 unmodified line301 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)309 310 # Receive the response from the server311 try:312 try: # Python 2.7+, use buffering of HTTP responses3 unmodified lines316 except SocketTimeout:317 raise ReadTimeoutError(318 self, url, "Read timed out. (read timeout=%s)" % read_timeout)319 320+ 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.")327+328+ raise329+330 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)337+338 raise339 409-340 # 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 lines488 # ``response.read()``)489 490 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.")493 565- except SocketTimeout:566- # Timed out by socket567- raise ReadTimeoutError(self, url, "Read timed out.")568-494 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)496 497 except CertificateError as e:498 # Name mismatch499 raise SSLError(e)500 501+ except TimeoutError as e:502+ # Connection broken, discard.503+ conn = None504+ # Save the error off for retry logic.505+ err = e506+507+ if retries == 0:508+ raise509+510 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 lines568 into an SSL socket.569 """570 571 scheme = 'https'572+ ConnectionCls = HTTPSConnection573 574 def __init__(self, host, port=None,575 strict=False, timeout=None, maxsize=1,576 block=False, headers=None,11 unmodified lines588 self.ssl_version = ssl_version589 self.assert_hostname = assert_hostname590 self.assert_fingerprint = assert_fingerprint591 661- 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 """597 667- 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_version606 607 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()617 687- return connection618+ return conn619 620 def _new_conn(self):621 """622 Return a fresh :class:`httplib.HTTPSConnection`.1 unmodified line624 self.num_connections += 1625 log.info("Starting new HTTPS connection (%d): %s"626 % (self.num_connections, self.host))627 628+ 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.")632+633 actual_host = self.host634 actual_port = self.port635 if self.proxy is not None:636 actual_host = self.proxy.host637 actual_port = self.proxy.port638 703- 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 = VerifiedHTTPSConnection710-639 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)642 718- return self._prepare_conn(connection)643+ conn = self.ConnectionCls(host=actual_host, port=actual_port,644+ timeout=self.timeout.connect_timeout,645+ **extra_params)646 647+ return self._prepare_conn(conn)648 649+650 def connection_from_url(url, **kw):651 """652 Given a url, return an :class:`.ConnectionPool` instance of its host.653 21 unmodified linesmodified:requests/packages/urllib3/util.py+24 added-15 removed
78 unmodified lines79 80 :type read: integer, float, or None81 82 :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.87 88 Defaults to None.89 90-90 :type total: integer, float, or None91 92 .. note::93 5 unmodified lines99 urllib3 to return a response may be greater than the value passed to100 `total`.101 102 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.110+111+ 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 """115 116 #: A sentinel object representing the default timeout value117 DEFAULT_TIMEOUT = _GLOBAL_DEFAULT_TIMEOUT118 115- 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 = None251 unmodified lines375 path = delim + path_376 377 # Auth378 if '@' in url:379+ # Last '@' denotes end of auth part375- auth, url = url.split('@', 1)380+ auth, url = url.rsplit('@', 1)381 382 # IPv6383 if url and url[0] == '[':384 host, url = url.split(']', 1)5 unmodified lines390 391 if not host:392 host = _host393 394+ 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 = None402 392- port = int(port)393-403 elif not host and url:404 host = url405 406 if not path:229 unmodified lines