Merge remote-tracking branch 'origin/master'
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 · parents b2db089, fe4c4f1 · Browse files · 14 files·+224 added−80 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
14 files+224 added−80 removed
- other:+224 added−80 removed
Provenance
- Commit
a3cd2f3- Tree
ad25e31- Author
Kenneth Reitz <me@kennethreitz.com>- Committer
Kenneth Reitz <me@kennethreitz.com>- Parent 1
b2db089- Parent 2
fe4c4f1
14 files changed+224 added−80 removed
modified:docs/community/faq.rst+23 added
58 unmodified lines59 * Python 3.160 * Python 3.261 * Python 3.362 * PyPy 1.963+64+What are "hostname doesn't match" errors?65+-----------------------------------------66+67+These errors occur when :ref:`SSL certificate verification <verification>`68+fails to match the certificate the server responds with to the hostname69+Requests thinks it's contacting. If you're certain the server's SSL setup is70+correct (for example, because you can visit the site with your browser) and71+you're using Python 2.6 or 2.7, a possible explanation is that you need72+Server-Name-Indication.73+74+`Server-Name-Indication`_, or SNI, is an official extension to SSL where the75+client tells the server what hostname it is contacting. This enables `virtual76+hosting`_ on SSL protected sites, the server being to able to respond with a77+certificate appropriate for the hostname the client is contacting.78+79+Python3's SSL module includes native support for SNI. This support has not been80+back ported to Python2. For information on using SNI with Requests on Python281+refer to this `Stack Overflow answer`_.82+83+.. _`Server-Name-Indication`: https://en.wikipedia.org/wiki/Server_Name_Indication84+.. _`virtual hosting`: https://en.wikipedia.org/wiki/Virtual_hosting85+.. _`Stack Overflow answer`: https://stackoverflow.com/questions/18578439/using-requests-with-tls-doesnt-give-sni-support/18579484#18579484modified:docs/user/advanced.rst+2 added
143 unmodified lines144 )145 146 print(resp.status_code)147 148+.. _verification:149+150 SSL Cert Verification151 ---------------------152 153 Requests can verify SSL certificates for HTTPS requests, just like a web browser. To check a host's SSL certificate, you can use the ``verify`` argument::529 unmodified linesmodified:docs/api.rst+3 added-1 removed
247 unmodified lines248 they will be converted to the native string type assuming UTF-8 encoding.249 250 * Timeouts behave slightly differently. On streaming requests, the timeout251 only applies to the connection attempt. On regular requests, the timeout252- is applied to the connection process and downloading the full body.252+ is applied to the connection process and on to all attempts to read data from253+ the underlying socket. It does *not* apply to the total download time for the254+ request.255 256 ::257 258 tarball_url = 'https://github.com/kennethreitz/requests/tarball/master'9 unmodified linesmodified:requests/__init__.py+2 added-2 removed
40 unmodified lines41 42 """43 44 __title__ = 'requests'45-__version__ = '2.2.1'46-__build__ = 0x02020145+__version__ = '2.3.0'46+__build__ = 0x02030047 __author__ = 'Kenneth Reitz'48 __license__ = 'Apache 2.0'49 __copyright__ = 'Copyright 2014 Kenneth Reitz'50 27 unmodified linesmodified:requests/adapters.py+5 added-8 removed
308 unmodified lines309 self.add_headers(request)310 311 chunked = not (request.body is None or 'Content-Length' in request.headers)312 313- if stream:314- timeout = TimeoutSauce(connect=timeout)315- else:316- timeout = TimeoutSauce(connect=timeout, read=timeout)313+ timeout = TimeoutSauce(connect=timeout, read=timeout)314 315 try:316 if not chunked:317 resp = conn.urlopen(50 unmodified lines368 # All is well, return the connection to the pool.369 conn._put_conn(low_conn)370 371 except socket.error as sockerr:375- raise ConnectionError(sockerr)372+ raise ConnectionError(sockerr, request=request)373 374 except MaxRetryError as e:378- raise ConnectionError(e)375+ raise ConnectionError(e, request=request)376 377 except _ProxyError as e:378 raise ProxyError(e)379 380 except (_SSLError, _HTTPError) as e:381 if isinstance(e, _SSLError):385- raise SSLError(e)382+ raise SSLError(e, request=request)383 elif isinstance(e, TimeoutError):387- raise Timeout(e)384+ raise Timeout(e, request=request)385 else:386 raise387 388 r = self.build_response(request, resp)5 unmodified linesmodified:requests/api.py+1 added-1 removed
24 unmodified lines25 :param headers: (optional) Dictionary of HTTP Headers to send with the :class:`Request`.26 :param cookies: (optional) Dict or CookieJar object to send with the :class:`Request`.27 :param files: (optional) Dictionary of 'name': file-like-objects (or {'name': ('filename', fileobj)}) for multipart encoding upload.28 :param auth: (optional) Auth tuple to enable Basic/Digest/Custom HTTP Auth.29- :param timeout: (optional) Float describing the timeout of the request.29+ :param timeout: (optional) Float describing the timeout of the request in seconds.30 :param allow_redirects: (optional) Boolean. Set to True if POST/PUT/DELETE redirect following is allowed.31 :param proxies: (optional) Dictionary mapping protocol to the URL of the proxy.32 :param verify: (optional) if ``True``, the SSL cert will be verified. A CA_BUNDLE path can also be provided.33 :param stream: (optional) if ``False``, the response content will be immediately downloaded.87 unmodified linesmodified:requests/auth.py-3 removed
9 unmodified lines10 import os11 import re12 import time13 import hashlib14-import logging14 15 from base64 import b64encode16 17 from .compat import urlparse, str18 from .cookies import extract_cookies_to_jar19 from .utils import parse_dict_header20 22-log = logging.getLogger(__name__)23-21 CONTENT_TYPE_FORM_URLENCODED = 'application/x-www-form-urlencoded'22 CONTENT_TYPE_MULTI_PART = 'multipart/form-data'23 24 169 unmodified linesmodified:requests/exceptions.py+12 added-5 removed
12 unmodified lines13 class RequestException(IOError):14 """There was an ambiguous exception that occurred while handling your15 request."""16 17+ def __init__(self, *args, **kwargs):18+ """19+ Initialize RequestException with `request` and `response` objects.20+ """21+ response = kwargs.pop('response', None)22+ self.response = response23+ self.request = kwargs.pop('request', None)24+ if (response is not None and not self.request and25+ hasattr(response, 'request')):26+ self.request = self.response.request27+ super(RequestException, self).__init__(*args, **kwargs)28 29+30 class HTTPError(RequestException):31 """An HTTP error occurred."""32 21- def __init__(self, *args, **kwargs):22- """ Initializes HTTPError with optional `response` object. """23- self.response = kwargs.pop('response', None)24- super(HTTPError, self).__init__(*args, **kwargs)33 26-34 class ConnectionError(RequestException):35 """A Connection error occurred."""36 37 38 unmodified linesmodified:requests/models.py+29 added-7 removed
6 unmodified lines7 This module contains the primary objects that power Requests.8 """9 10 import collections11-import logging11 import datetime12 13 from io import BytesIO, UnsupportedOperation14 from .hooks import default_hooks14 unmodified lines29 iter_slices, guess_json_utf, super_len, to_native_string)30 from .compat import (31 cookielib, urlunparse, urlsplit, urlencode, str, bytes, StringIO,32 is_py2, chardet, json, builtin_str, basestring, IncompleteRead)33+from .status_codes import codes34 35+#: The set of HTTP status codes that indicate an automatically36+#: processable redirect.37+REDIRECT_STATI = (38+ codes.moved, # 30139+ codes.found, # 30240+ codes.other, # 30341+ codes.temporary_moved, # 30742+)43+DEFAULT_REDIRECT_LIMIT = 3044 CONTENT_CHUNK_SIZE = 10 * 102445 ITER_CHUNK_SIZE = 51246 38-log = logging.getLogger(__name__)47 40-48 class RequestEncodingMixin(object):49 @property50 def path_url(self):51 """Build the path URL to use."""471 unmodified lines523 524 self._content = False525 self._content_consumed = False526 520- #: Integer Code of responded HTTP Status.527+ #: Integer Code of responded HTTP Status, e.g. 404 or 200.528 self.status_code = None529 530 #: Case-insensitive Dictionary of Response Headers.531 #: For example, ``headers['content-encoding']`` will return the15 unmodified lines547 #: the history of the Request. Any redirect responses will end548 #: up here. The list is sorted from the oldest to the most recent request.549 self.history = []550 551+ #: Textual reason of responded HTTP Status, e.g. "Not Found" or "OK".552 self.reason = None553 554 #: A CookieJar of Cookies the server sent back.555 self.cookies = cookiejar_from_dict({})18 unmodified lines574 setattr(self, name, value)575 576 # pickled objects do not have .raw577 setattr(self, '_content_consumed', True)578+ setattr(self, 'raw', None)579 580 def __repr__(self):581 return '<Response [%s]>' % (self.status_code)582 17 unmodified lines600 return False601 return True602 603 @property604+ def is_redirect(self):605+ """True if this Response is a well-formed HTTP redirect that could have606+ been processed automatically (by :meth:`Session.resolve_redirects`).607+ """608+ return ('location' in self.headers and self.status_code in REDIRECT_STATI)609+610+ @property611 def apparent_encoding(self):596- """The apparent encoding, provided by the lovely Charade library597- (Thanks, Ian!)."""612+ """The apparent encoding, provided by the chardet library"""613 return chardet.detect(self.content)['encoding']614 615 def iter_content(self, chunk_size=1, decode_unicode=False):616 """Iterates over the response data. When stream=True is set on the132 unmodified lines749 # decoding fails, fall back to `self.text` (using chardet to make750 # a best guess).751 encoding = guess_json_utf(self.content)752 if encoding is not None:753+ try:738- return json.loads(self.content.decode(encoding), **kwargs)754+ return json.loads(self.content.decode(encoding), **kwargs)755+ except UnicodeDecodeError:756+ # Wrong UTF codec detected; usually because it's not UTF-8757+ # but some other 8-bit codec. This is an RFC violation,758+ # and the server didn't bother to tell us what codec *was*759+ # used.760+ pass761 return json.loads(self.text, **kwargs)762 763 @property764 def links(self):37 unmodified linesmodified:requests/sessions.py+78 added-25 removed
10 unmodified lines11 import os12 from collections import Mapping13 from datetime import datetime14 15+from .auth import _basic_auth_str16 from .compat import cookielib, OrderedDict, urljoin, urlparse, builtin_str17 from .cookies import (18 cookiejar_from_dict, extract_cookies_to_jar, RequestsCookieJar, merge_cookies)18-from .models import Request, PreparedRequest19+from .models import Request, PreparedRequest, DEFAULT_REDIRECT_LIMIT20 from .hooks import default_hooks, dispatch_hook21 from .utils import to_key_val_list, default_headers, to_native_string22 from .exceptions import TooManyRedirects, InvalidSchema23 from .structures import CaseInsensitiveDict24 25 from .adapters import HTTPAdapter26 26-from .utils import requote_uri, get_environ_proxies, get_netrc_auth27+from .utils import (28+ requote_uri, get_environ_proxies, get_netrc_auth, should_bypass_proxies,29+ get_auth_from_url30+)31 32 from .status_codes import codes29-REDIRECT_STATI = (30- codes.moved, # 30131- codes.found, # 30232- codes.other, # 30333- codes.temporary_moved, # 30734-)35-DEFAULT_REDIRECT_LIMIT = 3033 34+# formerly defined here, reexposed here for backward compatibility35+from .models import REDIRECT_STATI36 37+38 def merge_setting(request_setting, session_setting, dict_class=OrderedDict):39 """40 Determines appropriate setting for a given request, taking into account the41 explicit setting on that request, and the setting in the session. If a20 unmodified lines62 for (k, v) in request_setting.items():63 if v is None:64 del merged_setting[k]65 66+ merged_setting = dict((k, v) for (k, v) in merged_setting.items() if v is not None)67+68 return merged_setting69 70 71 def merge_hooks(request_hooks, session_hooks, dict_class=OrderedDict):18 unmodified lines90 """Receives a Response. Returns a generator of Responses."""91 92 i = 093 92- # ((resp.status_code is codes.see_other))93- while ('location' in resp.headers and resp.status_code in REDIRECT_STATI):94+ while resp.is_redirect:95 prepared_request = req.copy()96 97 resp.content # Consume socket so it can be released98 58 unmodified lines157 extract_cookies_to_jar(prepared_request._cookies, prepared_request, resp.raw)158 prepared_request._cookies.update(self.cookies)159 prepared_request.prepare_cookies(prepared_request._cookies)160 160- if 'Authorization' in headers:161- # If we get redirected to a new host, we should strip out any162- # authentication headers.163- original_parsed = urlparse(resp.request.url)164- redirect_parsed = urlparse(url)161+ # Rebuild auth and proxy information.162+ proxies = self.rebuild_proxies(prepared_request, proxies)163+ self.rebuild_auth(prepared_request, resp)164 166- if (original_parsed.hostname != redirect_parsed.hostname):167- del headers['Authorization']168-169- # .netrc might have more auth for us.170- new_auth = get_netrc_auth(url) if self.trust_env else None171- if new_auth is not None:172- prepared_request.prepare_auth(new_auth)173-165 resp = self.send(166 prepared_request,167 stream=stream,168 timeout=timeout,7 unmodified lines176 177 i += 1178 yield resp179 180+ def rebuild_auth(self, prepared_request, response):181+ """182+ When being redirected we may want to strip authentication from the183+ request to avoid leaking credentials. This method intelligently removes184+ and reapplies authentication where possible to avoid credential loss.185+ """186+ headers = prepared_request.headers187+ url = prepared_request.url188 189+ if 'Authorization' in headers:190+ # If we get redirected to a new host, we should strip out any191+ # authentication headers.192+ original_parsed = urlparse(response.request.url)193+ redirect_parsed = urlparse(url)194+195+ if (original_parsed.hostname != redirect_parsed.hostname):196+ del headers['Authorization']197+198+ # .netrc might have more auth for us on our new host.199+ new_auth = get_netrc_auth(url) if self.trust_env else None200+ if new_auth is not None:201+ prepared_request.prepare_auth(new_auth)202+203+ return204+205+ def rebuild_proxies(self, prepared_request, proxies):206+ """207+ This method re-evaluates the proxy configuration by considering the208+ environment variables. If we are redirected to a URL covered by209+ NO_PROXY, we strip the proxy configuration. Otherwise, we set missing210+ proxy keys for this URL (in case they were stripped by a previous211+ redirect).212+213+ This method also replaces the Proxy-Authorization header where214+ necessary.215+ """216+ headers = prepared_request.headers217+ url = prepared_request.url218+ new_proxies = {}219+220+ if not should_bypass_proxies(url):221+ environ_proxies = get_environ_proxies(url)222+ scheme = urlparse(url).scheme223+224+ proxy = environ_proxies.get(scheme)225+226+ if proxy:227+ new_proxies.setdefault(scheme, environ_proxies[scheme])228+229+ if 'Proxy-Authorization' in headers:230+ del headers['Proxy-Authorization']231+232+ try:233+ username, password = get_auth_from_url(new_proxies[scheme])234+ except KeyError:235+ username, password = None, None236+237+ if username and password:238+ headers['Proxy-Authorization'] = _basic_auth_str(username, password)239+240+ return new_proxies241+242+243 class Session(SessionRedirectMixin):244 """A Requests session.245 246 Provides cookie persistence, connection-pooling, and configuration.138 unmodified lines385 for multipart encoding upload.386 :param auth: (optional) Auth tuple or callable to enable387 Basic/Digest/Custom HTTP Auth.388 :param timeout: (optional) Float describing the timeout of the336- request.389+ request in seconds.390 :param allow_redirects: (optional) Boolean. Set to True by default.391 :param proxies: (optional) Dictionary mapping protocol to the URL of392 the proxy.393 :param stream: (optional) whether to immediately download the response234 unmodified linesmodified:requests/utils.py+16 added-11 removed
464 unmodified lines465 return False466 return True467 468 469-def get_environ_proxies(url):470- """Return a dict of environment proxies."""471-469+def should_bypass_proxies(url):470+ """471+ Returns whether we should bypass proxies or not.472+ """473 get_proxy = lambda k: os.environ.get(k) or os.environ.get(k.upper())474 475 # First check whether no_proxy is defined. If it is, check that the URL476 # we're getting isn't in the no_proxy list.9 unmodified lines486 if is_ipv4_address(ip):487 for proxy_ip in no_proxy:488 if is_valid_cidr(proxy_ip):489 if address_in_network(ip, proxy_ip):489- return {}490+ return True491 else:492 for host in no_proxy:493 if netloc.endswith(host) or netloc.split(':')[0].endswith(host):494 # The URL does match something in no_proxy, so we don't want495 # to apply the proxies on this URL.495- return {}496+ return True497 498 # If the system proxy settings indicate that this URL should be bypassed,499 # don't proxy.500 # The proxy_bypass function is incredibly buggy on OS X in early versions5 unmodified lines506 except (TypeError, socket.gaierror):507 bypass = False508 509 if bypass:509- return {}510+ return True511 511- # If we get here, we either didn't have no_proxy set or we're not going512- # anywhere that no_proxy applies to, and the system settings don't require513- # bypassing the proxy for the current URL.514- return getproxies()512+ return False513 514+def get_environ_proxies(url):515+ """Return a dict of environment proxies."""516+ if should_bypass_proxies(url):517+ return {}518+ else:519+ return getproxies()520 521+522 def default_user_agent(name="python-requests"):523 """Return a string representing the default user agent."""524 _implementation = platform.python_implementation()525 26 unmodified lines552 553 def default_headers():554 return CaseInsensitiveDict({555 'User-Agent': default_user_agent(),551- 'Accept-Encoding': ', '.join(('gzip', 'deflate', 'compress')),556+ 'Accept-Encoding': ', '.join(('gzip', 'deflate')),557 'Accept': '*/*'558 })559 560 108 unmodified linesmodified:HISTORY.rst+13 added
1 unmodified line2 3 Release History4 ---------------5 6+2.3.0 (YYYY-MM-DD)7+++++++++++++++++++8+9+**API Changes**10+11+- New ``Response`` property ``is_redirect``, which is true when the12+ library could have processed this response as a redirection (whether13+ or not it actually did).14+- The ``timeout`` parameter now affects requests with both ``stream=True`` and15+ ``stream=False`` equally.16+17 2.2.1 (2014-01-23)18 ++++++++++++++++++19 20 **Bugfixes**117 unmodified lines138 139 1.2.1 (2013-05-20)140 ++++++++++++++++++141 142+- 301 and 302 redirects now change the verb to GET for all verbs, not just143+ POST, improving browser compatibility.144 - Python 3.3.2 compatibility145 - Always percent-encode location headers146 - Fix connection adapter matching to be most-specific first147 - new argument to the default connection adapter for passing a block argument635 unmodified linesmodified:NOTICE+5 added-17 removed
22 unmodified lines23 FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR24 OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER25 DEALINGS IN THE SOFTWARE.26 27-Charade License28-================27+Chardet License28+===============29 30 This library is free software; you can redistribute it and/or31 modify it under the terms of the GNU Lesser General Public32 License as published by the Free Software Foundation; either12 unmodified lines45 46 CA Bundle License47 =================48 49-This library is free software; you can redistribute it and/or50-modify it under the terms of the GNU Lesser General Public51-License as published by the Free Software Foundation; either52-version 2.1 of the License, or (at your option) any later version.53-54-This library is distributed in the hope that it will be useful,55-but WITHOUT ANY WARRANTY; without even the implied warranty of56-MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU57-Lesser General Public License for more details.58-59-You should have received a copy of the GNU Lesser General Public60-License along with this library; if not, write to the Free Software61-Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA62-02110-130163-49+This Source Code Form is subject to the terms of the Mozilla Public50+License, v. 2.0. If a copy of the MPL was not distributed with this51+file, You can obtain one at http://mozilla.org/MPL/2.0/.modified:test_requests.py+35 added
15 unmodified lines16 from requests.compat import (17 Morsel, cookielib, getproxies, str, urljoin, urlparse)18 from requests.cookies import cookiejar_from_dict, morsel_to_cookie19 from requests.exceptions import InvalidURL, MissingSchema20+from requests.models import PreparedRequest, Response21 from requests.structures import CaseInsensitiveDict22 23 try:24 import StringIO90 unmodified lines115 116 def test_HTTP_302_ALLOW_REDIRECT_GET(self):117 r = requests.get(httpbin('redirect', '1'))118 assert r.status_code == 200119+ assert r.history[0].status_code == 302120+ assert r.history[0].is_redirect121 122 # def test_HTTP_302_ALLOW_REDIRECT_POST(self):123 # r = requests.post(httpbin('status', '302'), data={'some': 'data'})124 # self.assertEqual(r.status_code, 200)86 unmodified lines211 urls = [r.url for r in resp.history]212 req_urls = [r.request.url for r in resp.history]213 assert urls == req_urls214 215+ def test_headers_on_session_with_None_are_not_sent(self):216+ """Do not send headers in Session.headers with None values."""217+ ses = requests.Session()218+ ses.headers['Accept-Encoding'] = None219+ req = requests.Request('GET', 'http://httpbin.org/get')220+ prep = ses.prepare_request(req)221+ assert 'Accept-Encoding' not in prep.headers222+223 def test_user_agent_transfers(self):224 225 heads = {226 'User-agent': 'Mozilla/5.0 (github.com/kennethreitz/requests)'638 unmodified lines865 req = requests.Request('GET', test_url)866 preq = req.prepare()867 assert test_url == preq.url868 869+ def test_auth_is_stripped_on_redirect_off_host(self):870+ r = requests.get(871+ httpbin('redirect-to'),872+ params={'url': 'http://www.google.co.uk'},873+ auth=('user', 'pass'),874+ )875+ assert r.history[0].request.headers['Authorization']876+ assert not r.request.headers.get('Authorization', '')877 878+ def test_auth_is_retained_for_redirect_on_host(self):879+ r = requests.get(httpbin('redirect/1'), auth=('user', 'pass'))880+ h1 = r.history[0].request.headers['Authorization']881+ h2 = r.request.headers['Authorization']882+883+ assert h1 == h2884+885+886 class TestContentEncodingDetection(unittest.TestCase):887 888 def test_none(self):889 encodings = requests.utils.get_encodings_from_content('')305 unmodified lines1195 with pytest.raises(TypeError):1196 morsel_to_cookie(morsel)1197 1198 1199+class TestTimeout:1200+ def test_stream_timeout(self):1201+ try:1202+ r = requests.get('https://httpbin.org/delay/10', timeout=5.0)1203+ except requests.exceptions.Timeout as e:1204+ assert 'Read timed out' in e.args[0].args[0]1205+1206+1207 if __name__ == '__main__':1208 unittest.main()