Merge branch 'develop' of https://github.com/kennethreitz/requests into urllib3-attribution
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by Andrey Petrov · committed by Andrey Petrov · parents 534cdd7, 14e8eea · Browse files · 7 files·+67 added−40 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+67 added−40 removed
- other:+67 added−40 removed
Provenance
- Commit
68619b8- Tree
72b6796- Author
Andrey Petrov <andrey.petrov@shazow.net>- Committer
Andrey Petrov <andrey.petrov@shazow.net>- Parent 1
534cdd7- Parent 2
14e8eea
7 files changed+67 added−40 removed
modified:docs/user/advanced.rst+2 added-2 removed
51 unmodified lines52 53 >>> requests.get('https://kennethreitz.com', verify=True)54 requests.exceptions.SSLError: hostname 'kennethreitz.com' doesn't match either of '*.herokuapp.com', 'herokuapp.com'55 56-I don't have SSL setup on this domain, so it fails. Excellent. I do have certs for httpbin.org though::56+I don't have SSL setup on this domain, so it fails. Excellent. Github does though::57 58- >>> requests.get('https://httpbin.org', verify=True)58+ >>> requests.get('https://github.com', verify=True)59 <Response [200]>60 61 You can also pass ``verify`` the path to a CA_BUNDLE file for private certs. You can also set the ``REQUESTS_CA_BUNDLE`` environment variable.62 231 unmodified linesmodified:requests/packages/urllib3/connectionpool.py+9 added-13 removed
304 unmodified lines305 if headers is None:306 headers = self.headers307 308 if retries < 0:309- raise MaxRetryError("Max retries exceeded for url: %s" % url)309+ raise MaxRetryError(url)310 311 if timeout is _Default:312 timeout = self.timeout313 5 unmodified lines319 host = "%s://%s" % (self.scheme, self.host)320 if self.port:321 host = "%s:%d" % (host, self.port)322 323- raise HostChangedError("Connection pool with host '%s' tried to "324- "open a foreign host: %s" % (host, url))323+ raise HostChangedError(host, url, retries - 1)324 325 conn = None326 327 try:39 unmodified lines367 368 except (CertificateError), e:369 # Name mismatch370 raise SSLError(e)372- 371+372 except (HTTPException, SocketError), e:373 # Connection broken, discard. It will be replaced next _get_conn().374 conn = None375 7 unmodified lines383 "broken by '%r': %s" % (retries, e, url))384 return self.urlopen(method, url, body, headers, retries - 1,385 redirect, assert_same_host) # Try again386 388- # Handle redirection389- if (redirect and390- response.status in [301, 302, 303, 307] and391- 'location' in response.headers): # Redirect, retry392- log.info("Redirecting %s -> %s" %393- (url, response.headers.get('location')))394- return self.urlopen(method, response.headers.get('location'), body,395- headers, retries - 1, redirect,396- assert_same_host)387+ # Handle redirect?388+ redirect_location = redirect and response.get_redirect_location()389+ if redirect_location:390+ log.info("Redirecting %s -> %s" % (url, redirect_location))391+ return self.urlopen(method, redirect_location, body, headers,392+ retries - 1, redirect, assert_same_host)393 394 return response395 396 152 unmodified linesmodified:requests/packages/urllib3/exceptions.py+12 added-2 removed
16 unmodified lines17 18 19 class MaxRetryError(HTTPError):20 "Raised when the maximum number of retries is exceeded."21- pass21+ def __init__(self, url):22+ HTTPError.__init__(self, "Max retries exceeded for url: %s" % url)23+ self.url = url24 25 26 class TimeoutError(HTTPError):27 "Raised when a socket timeout occurs."1 unmodified line29 30 31 class HostChangedError(HTTPError):32 "Raised when an existing pool gets a request for a foreign host."31- pass33+ def __init__(self, original_host, new_url, retries=3):34+ HTTPError.__init__(self,35+ "Connection pool with host '%s' tried to open a foreign host: %s" %36+ (original_host, new_url))37 38+ self.original_host = original_host39+ self.new_url = new_url40+ self.retries = retries41+42+43 class EmptyPoolError(HTTPError):44 "Raised when a pool runs out of connections and no more are allowed."45 passmodified:requests/packages/urllib3/poolmanager.py+14 added-9 removed
2 unmodified lines3 #4 # This module is part of urllib3 and is released under5 # the MIT License: http://www.opensource.org/licenses/mit-license.php6 7+import logging8+9 from ._collections import RecentlyUsedContainer8-from .connectionpool import (9- HTTPConnectionPool, HTTPSConnectionPool,10- get_host, connection_from_url,11-)10+from .connectionpool import HTTPConnectionPool, HTTPSConnectionPool11+from .connectionpool import get_host, connection_from_url12+from .exceptions import HostChangedError13+from .request import RequestMethods14 15 16 __all__ = ['PoolManager', 'ProxyManager', 'proxy_from_url']17 18 17-from .request import RequestMethods18-from .connectionpool import HTTPConnectionPool, HTTPSConnectionPool19-20-19 pool_classes_by_scheme = {20 'http': HTTPConnectionPool,21 'https': HTTPSConnectionPool,22 }2 unmodified lines25 'http': 80,26 'https': 443,27 }28 29+log = logging.getLogger(__name__)30 31+32 class PoolManager(RequestMethods):33 """34 Allows for arbitrary requests while transparently keeping track of35 necessary connection pools for you.68 unmodified lines104 ``url`` must be absolute, such that an appropriate105 :class:`urllib3.connectionpool.ConnectionPool` can be chosen for it.106 """107 conn = self.connection_from_url(url)108+ try:108- return conn.urlopen(method, url, assert_same_host=False, **kw)109+ return conn.urlopen(method, url, **kw)110 111+ except HostChangedError, e:112+ kw['retries'] = e.retries # Persist retries countdown113+ return self.urlopen(method, e.new_url, **kw)114 115+116 class ProxyManager(RequestMethods):117 """118 Given a ConnectionPool to a proxy, the ProxyManager's ``urlopen`` method119 will make requests to any url through the defined proxy.14 unmodified linesmodified:requests/packages/urllib3/response.py+27 added-13 removed
82 unmodified lines83 84 if preload_content:85 self._body = self.read(decode_content=decode_content)86 87+ def get_redirect_location(self):88+ """89+ Should we redirect and where to?90+91+ :returns: Truthy redirect location string if we got a redirect status92+ code and valid location. ``None`` if redirect status and no93+ location. ``False`` if not a redirect status code.94+ """95+ if self.status in [301, 302, 303, 307]:96+ return self.headers.get('location')97+98+ return False99+100 def release_conn(self):101 if not self._pool or not self._connection:102 return103 6 unmodified lines110 if self._body:111 return self._body112 113 if self._fp:101- return self.read(decode_content=self._decode_content,102- cache_content=True)114+ return self.read(cache_content=True)115 104- def read(self, amt=None, decode_content=True, cache_content=False):116+ def read(self, amt=None, decode_content=None, cache_content=False):117 """118 Similar to :meth:`httplib.HTTPResponse.read`, but with two additional119 parameters: ``decode_content`` and ``cache_content``.120 14 unmodified lines135 set.)136 """137 content_encoding = self.headers.get('content-encoding')138 decoder = self.CONTENT_DECODERS.get(content_encoding)139+ if decode_content is None:140+ decode_content = self._decode_content141 142 data = self._fp and self._fp.read(amt)143 144 try:22 unmodified lines167 168 if self._original_response and self._original_response.isclosed():169 self.release_conn()170 157- @staticmethod158- def from_httplib(r, **response_kw):171+ @classmethod172+ def from_httplib(ResponseCls, r, **response_kw):173 """174 Given an :class:`httplib.HTTPResponse` instance ``r``, return a175 corresponding :class:`urllib3.response.HTTPResponse` object.176 177 Remaining parameters are passed to the HTTPResponse constructor, along178 with ``original_response=r``.179 """180 167- return HTTPResponse(body=r,168- headers=dict(r.getheaders()),169- status=r.status,170- version=r.version,171- reason=r.reason,172- strict=r.strict,173- original_response=r,174- **response_kw)181+ return ResponseCls(body=r,182+ headers=dict(r.getheaders()),183+ status=r.status,184+ version=r.version,185+ reason=r.reason,186+ strict=r.strict,187+ original_response=r,188+ **response_kw)189 190 # Backwards-compatibility methods for httplib.HTTPResponse191 def getheaders(self):192 return self.headers3 unmodified linesmodified:requests/models.py+1 added-1 removed
296 unmodified lines297 # Support for unicode domain names and paths.298 scheme, netloc, path, params, query, fragment = urlparse(self.url)299 300 if not scheme:301- raise ValueError()301+ raise ValueError("Invalid URL %r: No schema supplied" %self.url)302 303 netloc = netloc.encode('idna')304 305 if isinstance(path, unicode):403 unmodified linesmodified:AUTHORS.rst+2 added
67 unmodified lines68 - Christopher Davis69 - Ori Livneh70 - Jason Emerick71 - Bryan Helmig72+- Jonas Obrist73+