urllib3 v1.3
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 afb1bd1 · Browse files · 7 files·+190 added−162 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
7 files+190 added−162 removed
- other:+190 added−162 removed
Provenance
- Commit
21ccf8f- Tree
42cd32b- Author
Kenneth Reitz <me@kennethreitz.com>- Committer
Kenneth Reitz <me@kennethreitz.com>- Parent
afb1bd1
7 files changed+190 added−162 removed
modified:requests/packages/urllib3/__init__.py+6 added-12 removed
8 unmodified lines9 """10 11 __author__ = 'Andrey Petrov (andrey.petrov@shazow.net)'12 __license__ = 'MIT'13-__version__ = '1.2.2'13+__version__ = '1.3'14 15 16 from .connectionpool import (17 HTTPConnectionPool,18 HTTPSConnectionPool,19- connection_from_url,20- get_host,21- make_headers)19+ connection_from_url20+)21 23-24-from .exceptions import (25- HTTPError,26- MaxRetryError,27- SSLError,28- TimeoutError)29-22+from . import exceptions23+from .filepost import encode_multipart_formdata24 from .poolmanager import PoolManager, ProxyManager, proxy_from_url25 from .response import HTTPResponse32-from .filepost import encode_multipart_formdata26+from .util import make_headers, get_host27 28 29 # Set default logging handler to avoid "No handler found" warnings.30 import logging12 unmodified linesmodified:requests/packages/urllib3/connectionpool.py+13 added-121 removed
5 unmodified lines6 7 import logging8 import socket9 10-from base64 import b64encode10 from socket import error as SocketError, timeout as SocketTimeout11 13-try:14- from select import poll, POLLIN15-except ImportError: # Doesn't exist on OSX and other platforms16- from select import select17- poll = False18-12 try: # Python 313 from http.client import HTTPConnection, HTTPException14 from http.client import HTTP_PORT, HTTPS_PORT15 except ImportError:18 unmodified lines34 35 import ssl36 BaseSSLError = ssl.SSLError37 45-except ImportError:38+except (ImportError, AttributeError):39 pass40 41 49-from .packages.ssl_match_hostname import match_hostname, CertificateError42 from .request import RequestMethods43 from .response import HTTPResponse44+from .util import get_host, is_connection_dropped45 from .exceptions import (46 EmptyPoolError,47 HostChangedError,55- LocationParseError,48 MaxRetryError,49 SSLError,50 TimeoutError,51 )52 53 from .packages.ssl_match_hostname import match_hostname, CertificateError54 from .packages import six55 56+57 xrange = six.moves.xrange58 59 log = logging.getLogger(__name__)60 3 unmodified lines64 'http': HTTP_PORT,65 'https': HTTPS_PORT,66 }67 68+69 ## Connection objects (extension of httplib)70 71 class VerifiedHTTPSConnection(HTTPSConnection):72 """27 unmodified lines100 ca_certs=self.ca_certs)101 if self.ca_certs:102 match_hostname(self.sock.getpeercert(), self.host)103 104+105 ## Pool objects106 107 class ConnectionPool(object):108 """97 unmodified lines206 try:207 conn = self.pool.get(block=self.block, timeout=timeout)208 209 # If this is a persistent connection, check if it got disconnected215- if conn and conn.sock and is_connection_dropped(conn):210+ if conn and is_connection_dropped(conn):211 log.info("Resetting dropped connection: %s" % self.host)212 conn.close()213 214 except Empty:35 unmodified lines250 if timeout is _Default:251 timeout = self.timeout252 253 conn.timeout = timeout # This only does anything in Py26+259-254 conn.request(method, url, **httplib_request_kw)255+256+ # Set timeout257+ sock = getattr(conn, 'sock', False) # AppEngine doesn't have sock attr.258+ if sock:261- conn.sock.settimeout(timeout)259+ sock.settimeout(timeout)260+261 httplib_response = conn.getresponse()262 263 log.debug("\"%s %s %s\" %s %s" %264 (method, url,28 unmodified lines293 294 .. note::295 296 More commonly, it's appropriate to use a convenience method provided298- by :class:`.RequestMethods`, such as :meth:`.request`.297+ by :class:`.RequestMethods`, such as :meth:`request`.298 299 .. note::300 301 `release_conn` will only behave as expected if191 unmodified lines493 cert_reqs=self.cert_reqs, ca_certs=self.ca_certs)494 return connection495 496 498-## Helpers499-500-def make_headers(keep_alive=None, accept_encoding=None, user_agent=None,501- basic_auth=None):502- """503- Shortcuts for generating request headers.504-505- :param keep_alive:506- If ``True``, adds 'connection: keep-alive' header.507-508- :param accept_encoding:509- Can be a boolean, list, or string.510- ``True`` translates to 'gzip,deflate'.511- List will get joined by comma.512- String will be used as provided.513-514- :param user_agent:515- String representing the user-agent you want, such as516- "python-urllib3/0.6"517-518- :param basic_auth:519- Colon-separated username:password string for 'authorization: basic ...'520- auth header.521-522- Example: ::523-524- >>> make_headers(keep_alive=True, user_agent="Batman/1.0")525- {'connection': 'keep-alive', 'user-agent': 'Batman/1.0'}526- >>> make_headers(accept_encoding=True)527- {'accept-encoding': 'gzip,deflate'}528- """529- headers = {}530- if accept_encoding:531- if isinstance(accept_encoding, str):532- pass533- elif isinstance(accept_encoding, list):534- accept_encoding = ','.join(accept_encoding)535- else:536- accept_encoding = 'gzip,deflate'537- headers['accept-encoding'] = accept_encoding538-539- if user_agent:540- headers['user-agent'] = user_agent541-542- if keep_alive:543- headers['connection'] = 'keep-alive'544-545- if basic_auth:546- headers['authorization'] = 'Basic ' + \547- b64encode(six.b(basic_auth)).decode('utf-8')548-549- return headers550-551-552-def get_host(url):553- """554- Given a url, return its scheme, host and port (None if it's not there).555-556- For example: ::557-558- >>> get_host('http://google.com/mail/')559- ('http', 'google.com', None)560- >>> get_host('google.com:80')561- ('http', 'google.com', 80)562- """563-564- # This code is actually similar to urlparse.urlsplit, but much565- # simplified for our needs.566- port = None567- scheme = 'http'568-569- if '://' in url:570- scheme, url = url.split('://', 1)571- if '/' in url:572- url, _path = url.split('/', 1)573- if '@' in url:574- _auth, url = url.split('@', 1)575- if ':' in url:576- url, port = url.split(':', 1)577-578- if not port.isdigit():579- raise LocationParseError("Failed to parse: %s")580-581- port = int(port)582-583- return scheme, url, port584-585-497 def connection_from_url(url, **kw):498 """499 Given a url, return an :class:`.ConnectionPool` instance of its host.500 17 unmodified lines518 if scheme == 'https':519 return HTTPSConnectionPool(host, port=port, **kw)520 else:521 return HTTPConnectionPool(host, port=port, **kw)611-612-613-def is_connection_dropped(conn):614- """615- Returns True if the connection is dropped and should be closed.616-617- :param conn:618- ``HTTPConnection`` object.619- """620- if not poll: # Platform-specific621- return select([conn.sock], [], [], 0.0)[0]622-623- # This version is better on platforms that support it.624- p = poll()625- p.register(conn.sock, POLLIN)626- for (fno, ev) in p.poll(0.0):627- if fno == conn.sock.fileno():628- # Either data is buffered (bad), or the connection is dropped.629- return Truemodified:requests/packages/urllib3/filepost.py+19 added-5 removed
22 unmodified lines23 def get_content_type(filename):24 return mimetypes.guess_type(filename)[0] or 'application/octet-stream'25 26 27+def iter_fields(fields):28+ """29+ Iterate over fields.30+31+ Supports list of (k, v) tuples and dicts.32+ """33+ if isinstance(fields, dict):34+ return ((k, v) for k, v in six.iteritems(fields))35+36+ return ((k, v) for k, v in fields)37+38+39 def encode_multipart_formdata(fields, boundary=None):40 """41 Encode a dictionary of ``fields`` using the multipart/form-data mime format.42 43 :param fields:32- Dictionary of fields. The key is treated as the field name, and the33- value as the body of the form-data. If the value is a tuple of two34- elements, then the first element is treated as the filename of the35- form-data section.44+ Dictionary of fields or list of (key, value) field tuples. The key is45+ treated as the field name, and the value as the body of the form-data46+ bytes. If the value is a tuple of two elements, then the first element47+ is treated as the filename of the form-data section.48 49+ Field names and filenames must be unicode.50+51 :param boundary:52 If not specified, then a random boundary will be generated using53 :func:`mimetools.choose_boundary`.54 """55 body = BytesIO()56 if boundary is None:57 boundary = choose_boundary()58 45- for fieldname, value in six.iteritems(fields):59+ for fieldname, value in iter_fields(fields):60 body.write(b('--%s\r\n' % (boundary)))61 62 if isinstance(value, tuple):63 filename, data = value25 unmodified linesmodified:requests/packages/urllib3/poolmanager.py+2 added-2 removed
37 unmodified lines38 :class:`urllib3.connectionpool.ConnectionPool` instances.39 40 Example: ::41 42- >>> manager = PoolManager()42+ >>> 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/")46- >>> len(r.pools)46+ >>> len(manager.pools)47 248 49 """50 88 unmodified linesmodified:requests/packages/urllib3/request.py+1 added-20 removed
42 unmodified lines43 _encode_body_methods = set(['PATCH', 'POST', 'PUT', 'TRACE'])44 45 def urlopen(self, method, url, body=None, headers=None,46 encode_multipart=True, multipart_boundary=None,47- **kw):47+ **kw): # Abstract48 raise NotImplemented("Classes extending RequestMethods must implement "49 "their own ``urlopen`` method.")50 51 def request(self, method, url, fields=None, headers=None, **urlopen_kw):73 unmodified lines125 headers.update({'Content-Type': content_type})126 127 return self.urlopen(method, url, body=body, headers=headers,128 **urlopen_kw)129-130- # Deprecated:131-132- def get_url(self, url, fields=None, **urlopen_kw):133- """134- .. deprecated:: 1.0135- Use :meth:`request` instead.136- """137- return self.request_encode_url('GET', url, fields=fields,138- **urlopen_kw)139-140- def post_url(self, url, fields=None, headers=None, **urlopen_kw):141- """142- .. deprecated:: 1.0143- Use :meth:`request` instead.144- """145- return self.request_encode_body('POST', url, fields=fields,146- headers=headers,147- **urlopen_kw)modified:requests/packages/urllib3/response.py+13 added-2 removed
169 unmodified lines170 Remaining parameters are passed to the HTTPResponse constructor, along171 with ``original_response=r``.172 """173 174+ # Normalize headers between different versions of Python175+ headers = {}176+ for k, v in r.getheaders():177+ # Python 3: Header keys are returned capitalised178+ k = k.lower()179+180+ has_value = headers.get(k)181+ if has_value: # Python 3: Repeating header keys are unmerged.182+ v = ', '.join([has_value, v])183+184+ headers[k] = v185+186 # HTTPResponse objects in Python 3 don't have a .strict attribute187 strict = getattr(r, 'strict', 0)188 return ResponseCls(body=r,177- # In Python 3, the header keys are returned capitalised178- headers=dict((k.lower(), v) for k,v in r.getheaders()),189+ headers=headers,190 status=r.status,191 version=r.version,192 reason=r.reason,193 strict=strict,9 unmodified linesadded:requests/packages/urllib3/util.py+136 added
1+# urllib3/util.py2+# 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+7+8+from base64 import b64encode9+10+try:11+ from select import poll, POLLIN12+except ImportError: # `poll` doesn't exist on OSX and other platforms13+ poll = False14+ try:15+ from select import select16+ except ImportError: # `select` doesn't exist on AppEngine.17+ select = False18+19+from .packages import six20+from .exceptions import LocationParseError21+22+23+def make_headers(keep_alive=None, accept_encoding=None, user_agent=None,24+ basic_auth=None):25+ """26+ Shortcuts for generating request headers.27+28+ :param keep_alive:29+ If ``True``, adds 'connection: keep-alive' header.30+31+ :param accept_encoding:32+ Can be a boolean, list, or string.33+ ``True`` translates to 'gzip,deflate'.34+ List will get joined by comma.35+ String will be used as provided.36+37+ :param user_agent:38+ String representing the user-agent you want, such as39+ "python-urllib3/0.6"40+41+ :param basic_auth:42+ Colon-separated username:password string for 'authorization: basic ...'43+ auth header.44+45+ Example: ::46+47+ >>> make_headers(keep_alive=True, user_agent="Batman/1.0")48+ {'connection': 'keep-alive', 'user-agent': 'Batman/1.0'}49+ >>> make_headers(accept_encoding=True)50+ {'accept-encoding': 'gzip,deflate'}51+ """52+ headers = {}53+ if accept_encoding:54+ if isinstance(accept_encoding, str):55+ pass56+ elif isinstance(accept_encoding, list):57+ accept_encoding = ','.join(accept_encoding)58+ else:59+ accept_encoding = 'gzip,deflate'60+ headers['accept-encoding'] = accept_encoding61+62+ if user_agent:63+ headers['user-agent'] = user_agent64+65+ if keep_alive:66+ headers['connection'] = 'keep-alive'67+68+ if basic_auth:69+ headers['authorization'] = 'Basic ' + \70+ b64encode(six.b(basic_auth)).decode('utf-8')71+72+ return headers73+74+75+def get_host(url):76+ """77+ Given a url, return its scheme, host and port (None if it's not there).78+79+ For example: ::80+81+ >>> get_host('http://google.com/mail/')82+ ('http', 'google.com', None)83+ >>> get_host('google.com:80')84+ ('http', 'google.com', 80)85+ """86+87+ # This code is actually similar to urlparse.urlsplit, but much88+ # simplified for our needs.89+ port = None90+ scheme = 'http'91+92+ if '://' in url:93+ scheme, url = url.split('://', 1)94+ if '/' in url:95+ url, _path = url.split('/', 1)96+ if '@' in url:97+ _auth, url = url.split('@', 1)98+ if ':' in url:99+ url, port = url.split(':', 1)100+101+ if not port.isdigit():102+ raise LocationParseError("Failed to parse: %s" % url)103+104+ port = int(port)105+106+ return scheme, url, port107+108+109+110+def is_connection_dropped(conn):111+ """112+ Returns True if the connection is dropped and should be closed.113+114+ :param conn:115+ ``HTTPConnection`` object.116+117+ Note: For platforms like AppEngine, this will always return ``False`` to118+ let the platform handle connection recycling transparently for us.119+ """120+ sock = getattr(conn, 'sock', False)121+ if not sock: #Platform-specific: AppEngine122+ return False123+124+ if not poll: # Platform-specific125+ if not select: #Platform-specific: AppEngine126+ return False127+128+ return select([sock], [], [], 0.0)[0]129+130+ # This version is better on platforms that support it.131+ p = poll()132+ p.register(sock, POLLIN)133+ for (fno, ev) in p.poll(0.0):134+ if fno == sock.fileno():135+ # Either data is buffered (bad), or the connection is dropped.136+ return True