Skip to content
Myr

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

14 files+224 added−80 removed

modified:docs/community/faq.rst+23 added
58 unmodified lines
59* Python 3.160* Python 3.261* Python 3.362* PyPy 1.96364What are "hostname doesn't match" errors?65-----------------------------------------6667These errors occur when :ref:`SSL certificate verification <verification>`68fails to match the certificate the server responds with to the hostname69Requests thinks it's contacting. If you're certain the server's SSL setup is70correct (for example, because you can visit the site with your browser) and71you're using Python 2.6 or 2.7, a possible explanation is that you need72Server-Name-Indication.7374`Server-Name-Indication`_, or SNI, is an official extension to SSL where the75client tells the server what hostname it is contacting. This enables `virtual76hosting`_ on SSL protected sites, the server being to able to respond with a77certificate appropriate for the hostname the client is contacting.7879Python3's SSL module includes native support for SNI. This support has not been80back ported to Python2. For information on using SNI with Requests on Python281refer to this `Stack Overflow answer`_.8283.. _`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#18579484
modified:docs/user/advanced.rst+2 added
143 unmodified lines
144 )145146 print(resp.status_code)147148.. _verification:149150SSL Cert Verification151---------------------152153Requests 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 lines
modified:docs/api.rst+3 added-1 removed
247 unmodified lines
248 they will be converted to the native string type assuming UTF-8 encoding.249250* 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.255256 ::257258 tarball_url = 'https://github.com/kennethreitz/requests/tarball/master'
9 unmodified lines
modified:requests/__init__.py+2 added-2 removed
40 unmodified lines
4142"""4344__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 lines
modified:requests/adapters.py+5 added-8 removed
308 unmodified lines
309 self.add_headers(request)310311 chunked = not (request.body is None or 'Content-Length' in request.headers)312313 if stream:314 timeout = TimeoutSauce(connect=timeout)315 else:316 timeout = TimeoutSauce(connect=timeout, read=timeout)313 timeout = TimeoutSauce(connect=timeout, read=timeout)314315 try:316 if not chunked:317 resp = conn.urlopen(
50 unmodified lines
368 # All is well, return the connection to the pool.369 conn._put_conn(low_conn)370371 except socket.error as sockerr:375 raise ConnectionError(sockerr)372 raise ConnectionError(sockerr, request=request)373374 except MaxRetryError as e:378 raise ConnectionError(e)375 raise ConnectionError(e, request=request)376377 except _ProxyError as e:378 raise ProxyError(e)379380 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 raise387388 r = self.build_response(request, resp)
5 unmodified lines
modified:requests/api.py+1 added-1 removed
24 unmodified lines
25 :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 lines
modified:requests/auth.py-3 removed
9 unmodified lines
10import os11import re12import time13import hashlib14import logging1415from base64 import b64encode1617from .compat import urlparse, str18from .cookies import extract_cookies_to_jar19from .utils import parse_dict_header2022log = logging.getLogger(__name__)2321CONTENT_TYPE_FORM_URLENCODED = 'application/x-www-form-urlencoded'22CONTENT_TYPE_MULTI_PART = 'multipart/form-data'2324
169 unmodified lines
modified:requests/exceptions.py+12 added-5 removed
12 unmodified lines
13class RequestException(IOError):14 """There was an ambiguous exception that occurred while handling your15 request."""1617 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)282930class HTTPError(RequestException):31 """An HTTP error occurred."""3221 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)332634class ConnectionError(RequestException):35 """A Connection error occurred."""3637
38 unmodified lines
modified:requests/models.py+29 added-7 removed
6 unmodified lines
7This module contains the primary objects that power Requests.8"""910import collections11import logging11import datetime1213from io import BytesIO, UnsupportedOperation14from .hooks import default_hooks
14 unmodified lines
29 iter_slices, guess_json_utf, super_len, to_native_string)30from .compat import (31 cookielib, urlunparse, urlsplit, urlencode, str, bytes, StringIO,32 is_py2, chardet, json, builtin_str, basestring, IncompleteRead)33from .status_codes import codes3435#: The set of HTTP status codes that indicate an automatically36#: processable redirect.37REDIRECT_STATI = (38 codes.moved, # 30139 codes.found, # 30240 codes.other, # 30341 codes.temporary_moved, # 30742)43DEFAULT_REDIRECT_LIMIT = 3044CONTENT_CHUNK_SIZE = 10 * 102445ITER_CHUNK_SIZE = 5124638log = logging.getLogger(__name__)474048class RequestEncodingMixin(object):49 @property50 def path_url(self):51 """Build the path URL to use."""
471 unmodified lines
523524 self._content = False525 self._content_consumed = False526520 #: Integer Code of responded HTTP Status.527 #: Integer Code of responded HTTP Status, e.g. 404 or 200.528 self.status_code = None529530 #: Case-insensitive Dictionary of Response Headers.531 #: For example, ``headers['content-encoding']`` will return the
15 unmodified lines
547 #: 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 = []550551 #: Textual reason of responded HTTP Status, e.g. "Not Found" or "OK".552 self.reason = None553554 #: A CookieJar of Cookies the server sent back.555 self.cookies = cookiejar_from_dict({})
18 unmodified lines
574 setattr(self, name, value)575576 # pickled objects do not have .raw577 setattr(self, '_content_consumed', True)578 setattr(self, 'raw', None)579580 def __repr__(self):581 return '<Response [%s]>' % (self.status_code)582
17 unmodified lines
600 return False601 return True602603 @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)609610 @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']614615 def iter_content(self, chunk_size=1, decode_unicode=False):616 """Iterates over the response data. When stream=True is set on the
132 unmodified lines
749 # 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)762763 @property764 def links(self):
37 unmodified lines
modified:requests/sessions.py+78 added-25 removed
10 unmodified lines
11import os12from collections import Mapping13from datetime import datetime1415from .auth import _basic_auth_str16from .compat import cookielib, OrderedDict, urljoin, urlparse, builtin_str17from .cookies import (18 cookiejar_from_dict, extract_cookies_to_jar, RequestsCookieJar, merge_cookies)18from .models import Request, PreparedRequest19from .models import Request, PreparedRequest, DEFAULT_REDIRECT_LIMIT20from .hooks import default_hooks, dispatch_hook21from .utils import to_key_val_list, default_headers, to_native_string22from .exceptions import TooManyRedirects, InvalidSchema23from .structures import CaseInsensitiveDict2425from .adapters import HTTPAdapter2626from .utils import requote_uri, get_environ_proxies, get_netrc_auth27from .utils import (28 requote_uri, get_environ_proxies, get_netrc_auth, should_bypass_proxies,29 get_auth_from_url30)3132from .status_codes import codes29REDIRECT_STATI = (30 codes.moved, # 30131 codes.found, # 30232 codes.other, # 30333 codes.temporary_moved, # 30734)35DEFAULT_REDIRECT_LIMIT = 303334# formerly defined here, reexposed here for backward compatibility35from .models import REDIRECT_STATI363738def 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 a
20 unmodified lines
62 for (k, v) in request_setting.items():63 if v is None:64 del merged_setting[k]6566 merged_setting = dict((k, v) for (k, v) in merged_setting.items() if v is not None)6768 return merged_setting697071def merge_hooks(request_hooks, session_hooks, dict_class=OrderedDict):
18 unmodified lines
90 """Receives a Response. Returns a generator of Responses."""9192 i = 09392 # ((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()9697 resp.content # Consume socket so it can be released98
58 unmodified lines
157 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)160160 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)164166 if (original_parsed.hostname != redirect_parsed.hostname):167 del headers['Authorization']168169 # .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)173165 resp = self.send(166 prepared_request,167 stream=stream,168 timeout=timeout,
7 unmodified lines
176177 i += 1178 yield resp179180 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.url188189 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)194195 if (original_parsed.hostname != redirect_parsed.hostname):196 del headers['Authorization']197198 # .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)202203 return204205 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).212213 This method also replaces the Proxy-Authorization header where214 necessary.215 """216 headers = prepared_request.headers217 url = prepared_request.url218 new_proxies = {}219220 if not should_bypass_proxies(url):221 environ_proxies = get_environ_proxies(url)222 scheme = urlparse(url).scheme223224 proxy = environ_proxies.get(scheme)225226 if proxy:227 new_proxies.setdefault(scheme, environ_proxies[scheme])228229 if 'Proxy-Authorization' in headers:230 del headers['Proxy-Authorization']231232 try:233 username, password = get_auth_from_url(new_proxies[scheme])234 except KeyError:235 username, password = None, None236237 if username and password:238 headers['Proxy-Authorization'] = _basic_auth_str(username, password)239240 return new_proxies241242243class Session(SessionRedirectMixin):244 """A Requests session.245246 Provides cookie persistence, connection-pooling, and configuration.
138 unmodified lines
385 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 response
234 unmodified lines
modified:requests/utils.py+16 added-11 removed
464 unmodified lines
465 return False466 return True467468469def get_environ_proxies(url):470 """Return a dict of environment proxies."""471469def 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())474475 # 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 lines
486 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 True497498 # 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 versions
5 unmodified lines
506 except (TypeError, socket.gaierror):507 bypass = False508509 if bypass:509 return {}510 return True511511 # 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 False513514def get_environ_proxies(url):515 """Return a dict of environment proxies."""516 if should_bypass_proxies(url):517 return {}518 else:519 return getproxies()520521522def default_user_agent(name="python-requests"):523 """Return a string representing the default user agent."""524 _implementation = platform.python_implementation()525
26 unmodified lines
552553def 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 })559560
108 unmodified lines
modified:HISTORY.rst+13 added
1 unmodified line
23Release History4---------------562.3.0 (YYYY-MM-DD)7++++++++++++++++++89**API Changes**1011- 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.16172.2.1 (2014-01-23)18++++++++++++++++++1920**Bugfixes**
117 unmodified lines
1381391.2.1 (2013-05-20)140++++++++++++++++++141142- 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 argument
635 unmodified lines
modified:NOTICE+5 added-17 removed
22 unmodified lines
23FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR24OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER25DEALINGS IN THE SOFTWARE.2627Charade License28================27Chardet License28===============2930This library is free software; you can redistribute it and/or31modify it under the terms of the GNU Lesser General Public32License as published by the Free Software Foundation; either
12 unmodified lines
4546CA Bundle License47=================4849This library is free software; you can redistribute it and/or50modify it under the terms of the GNU Lesser General Public51License as published by the Free Software Foundation; either52version 2.1 of the License, or (at your option) any later version.5354This library is distributed in the hope that it will be useful,55but WITHOUT ANY WARRANTY; without even the implied warranty of56MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU57Lesser General Public License for more details.5859You should have received a copy of the GNU Lesser General Public60License along with this library; if not, write to the Free Software61Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA6202110-13016349This Source Code Form is subject to the terms of the Mozilla Public50License, v. 2.0. If a copy of the MPL was not distributed with this51file, You can obtain one at http://mozilla.org/MPL/2.0/.
modified:test_requests.py+35 added
15 unmodified lines
16from requests.compat import (17 Morsel, cookielib, getproxies, str, urljoin, urlparse)18from requests.cookies import cookiejar_from_dict, morsel_to_cookie19from requests.exceptions import InvalidURL, MissingSchema20from requests.models import PreparedRequest, Response21from requests.structures import CaseInsensitiveDict2223try:24 import StringIO
90 unmodified lines
115116 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_redirect121122 # 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 lines
211 urls = [r.url for r in resp.history]212 req_urls = [r.request.url for r in resp.history]213 assert urls == req_urls214215 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.headers222223 def test_user_agent_transfers(self):224225 heads = {226 'User-agent': 'Mozilla/5.0 (github.com/kennethreitz/requests)'
638 unmodified lines
865 req = requests.Request('GET', test_url)866 preq = req.prepare()867 assert test_url == preq.url868869 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', '')877878 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']882883 assert h1 == h2884885886class TestContentEncodingDetection(unittest.TestCase):887888 def test_none(self):889 encodings = requests.utils.get_encodings_from_content('')
305 unmodified lines
1195 with pytest.raises(TypeError):1196 morsel_to_cookie(morsel)119711981199class 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]120512061207if __name__ == '__main__':1208 unittest.main()