merge
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 599a8f1, 07372dc · Browse files · 25 files·+381 added−78 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
25 files+381 added−78 removed
- tests:+150 added−6 removed
- other:+231 added−72 removed
Provenance
- Commit
6a74c70- Tree
c7370d2- Author
Kenneth Reitz <me@kennethreitz.org>- Committer
Kenneth Reitz <me@kennethreitz.org>- Parent 1
599a8f1- Parent 2
07372dc
25 files changed+381 added−78 removed
modified:docs/_templates/sidebarintro.html+5 added-5 removed
3 unmodified lines45678891011126 unmodified lines1920212223232425262719 unmodified lines474849505152535152535455565713 unmodified lines3 unmodified lines </a></p>
<p> <iframe src="http://ghbtns.com/github-btn.html?user=requests&repo=requests&type=watch&count=true&size=large" <iframe src="https://ghbtns.com/github-btn.html?user=requests&repo=requests&type=watch&count=true&size=large" allowtransparency="true" frameborder="0" scrolling="0" width="200px" height="35px"></iframe></p>
<p>6 unmodified lines<h3><a href="http://www.unixstickers.com/stickers/coding_stickers/requests-shaped-sticker">Stickers!</a></h3><h3>Stay Informed</h3><p>Receive updates on new releases and upcoming projects.</p>
<p><iframe src="http://ghbtns.com/github-btn.html?user=kennethreitz&type=follow&count=false"<p><iframe src="https://ghbtns.com/github-btn.html?user=kennethreitz&type=follow&count=false" allowtransparency="true" frameborder="0" scrolling="0" width="200" height="20"></iframe></p>
<p><a href="https://twitter.com/kennethreitz" class="twitter-follow-button" data-show-count="false">Follow @kennethreitz</a> <script>!function(d,s,id){var js,fjs=d.getElementsByTagName(s)[0],p=/^http:/.test(d.location)?'http':'https';if(!d.getElementById(id)){js=d.createElement(s);js.id=id;js.src=p+'://platform.twitter.com/widgets.js';fjs.parentNode.insertBefore(js,fjs);}}(document, 'script', 'twitter-wjs');</script></p><p><a href="https://saythanks.io/to/kennethreitz">Say Thanks!</a></p>19 unmodified lines <li><a href="http://docs.python-requests.org/en/latest/community/recommended/">Recommended Packages and Extensions</a></li>
<p></p>
<li><a href="http://github.com/requests/requests">Requests @ GitHub</a></li> <li><a href="http://pypi.python.org/pypi/requests">Requests @ PyPI</a></li> <li><a href="http://github.com/requests/requests/issues">Issue Tracker</a></li> <li><a href="https://github.com/requests/requests">Requests @ GitHub</a></li> <li><a href="https://pypi.python.org/pypi/requests">Requests @ PyPI</a></li> <li><a href="https://github.com/requests/requests/issues">Issue Tracker</a></li> <li><a href="http://docs.python-requests.org/en/latest/community/updates/#software-updates">Release History</a></li></ul>
13 unmodified linesmodified:docs/_templates/sidebarlogo.html+2 added-2 removed
2 unmodified lines34567789101112 unmodified lines2425262728282930313230 unmodified lines2 unmodified lines <img class="logo" src="{{ pathto('_static/requests-sidebar.png', 1) }}" title="https://kennethreitz.org/tattoos"/> </a></p><p><iframe src="http://ghbtns.com/github-btn.html?user=requests&repo=requests&type=watch&count=true&size=large"<iframe src="https://ghbtns.com/github-btn.html?user=requests&repo=requests&type=watch&count=true&size=large" allowtransparency="true" frameborder="0" scrolling="0" width="200px" height="35px"></iframe></p>
<p>12 unmodified lines<script async type="text/javascript" src="//cdn.carbonads.com/carbon.js?zoneid=1673&serve=C6AILKT&placement=pythonrequestsorg" id="_carbonads_js"></script>
<p>If you enjoy using this project, <a href="https://saythanks.io/to/kennethreitz">Say Thanks!</a></p>
<p><iframe src="http://ghbtns.com/github-btn.html?user=kennethreitz&type=follow&count=false"<p><iframe src="https://ghbtns.com/github-btn.html?user=kennethreitz&type=follow&count=false" allowtransparency="true" frameborder="0" scrolling="0" width="200" height="20"></iframe></p>
<p><a href="https://twitter.com/kennethreitz" class="twitter-follow-button" data-show-count="false">Follow @kennethreitz</a> <script>!function(d,s,id){var js,fjs=d.getElementsByTagName(s)[0],p=/^http:/.test(d.location)?'http':'https';if(!d.getElementById(id)){js=d.createElement(s);js.id=id;js.src=p+'://platform.twitter.com/widgets.js';fjs.parentNode.insertBefore(js,fjs);}}(document, 'script', 'twitter-wjs');</script></p>
30 unmodified linesmodified:docs/community/out-there.rst+1 added-1 removed
16 unmodified lines17 ================18 - `Python for the Web <http://gun.io/blog/python-for-the-web/>`_ teaches how to use Python to interact with the web, using Requests.19 - `Daniel Greenfeld's Review of Requests <http://pydanny.blogspot.com/2011/05/python-http-requests-for-humans.html>`_20 - `My 'Python for Humans' talk <http://python-for-humans.heroku.com>`_ ( `audio <http://codeconf.s3.amazonaws.com/2011/pycodeconf/talks/PyCodeConf2011%20-%20Kenneth%20Reitz.m4a>`_ )21-- `Issac Kelly's 'Consuming Web APIs' talk <http://issackelly.github.com/Consuming-Web-APIs-with-Python-Talk/slides/slides.html>`_21+- `Issac Kelly's 'Consuming Web APIs' talk <https://issackelly.github.com/Consuming-Web-APIs-with-Python-Talk/slides/slides.html>`_22 - `Blog post about Requests via Yum <http://arunsag.wordpress.com/2011/08/17/new-package-python-requests-http-for-humans/>`_23 - `Russian blog post introducing Requests <http://habrahabr.ru/blogs/python/126262/>`_24 - `Sending JSON in Requests <http://www.coglib.com/~icordasc/blog/2014/11/sending-json-in-requests.html>`_modified:docs/community/recommended.rst+1 added-1 removed
32 unmodified lines33 but do not belong in Requests proper. This library is actively maintained34 by members of the Requests core team, and reflects the functionality most35 requested by users within the community.36 37-.. _Requests-Toolbelt: http://toolbelt.readthedocs.io/en/latest/index.html37+.. _Requests-Toolbelt: https://toolbelt.readthedocs.io/en/latest/index.html38 39 40 Requests-Threads41 ----------------26 unmodified linesmodified:docs/dev/todo.rst+1 added-1 removed
59 unmodified lines60 61 Google AppEngine is not officially supported although support is available62 with the `Requests-Toolbelt`_.63 64-.. _Requests-Toolbelt: http://toolbelt.readthedocs.io/64+.. _Requests-Toolbelt: https://toolbelt.readthedocs.io/65 modified:docs/user/advanced.rst+29 added-5 removed
285 unmodified lines286 287 For the sake of security we recommend upgrading certifi frequently!288 289 .. _HTTP persistent connection: https://en.wikipedia.org/wiki/HTTP_persistent_connection290-.. _connection pooling: http://urllib3.readthedocs.io/en/latest/reference/index.html#module-urllib3.connectionpool290+.. _connection pooling: https://urllib3.readthedocs.io/en/latest/reference/index.html#module-urllib3.connectionpool291 .. _certifi: http://certifi.io/292 .. _Mozilla trust store: https://hg.mozilla.org/mozilla-central/raw-file/tip/security/nss/lib/ckfw/builtins/certdata.txt293 294 .. _body-content-workflow:140 unmodified lines435 You can assign a hook function on a per-request basis by passing a436 ``{hook_name: callback_function}`` dictionary to the ``hooks`` request437 parameter::438 439- hooks=dict(response=print_url)439+ hooks={'response': print_url}440 441 That ``callback_function`` will receive a chunk of data as its first442 argument.443 7 unmodified lines451 If the callback function returns a value, it is assumed that it is to452 replace the data that was passed in. If the function doesn't return453 anything, nothing else is effected.454 455+::456+457+ def record_hook(r, *args, **kwargs):458+ r.hook_called = True459+ return r460+461 Let's print some request method arguments at runtime::462 457- >>> requests.get('http://httpbin.org', hooks=dict(response=print_url))463+ >>> requests.get('http://httpbin.org', hooks={'response': print_url})464 http://httpbin.org465 <Response [200]>466 467+You can add multiple hooks to a single request. Let's call two hooks at once::468+469+ >>> r = requests.get('http://httpbin.org', hooks={'response': [print_url, record_hook]})470+ >>> r.hook_called471+ True472+473+You can also add hooks to a ``Session`` instance. Any hooks you add will then474+be called on every request made to the session. For example::475+476+ >>> s = requests.Session()477+ >>> s.hooks['response'].append(print_url)478+ >>> s.get('http://httpbin.org')479+ http://httpbin.org480+ <Response [200]>481+482+A ``Session`` can have multiple hooks, which will be called in the order483+they are added.484+485 .. _custom-auth:486 487 Custom Authentication488 ---------------------167 unmodified lines656 When you receive a response, Requests makes a guess at the encoding to657 use for decoding the response when you access the :attr:`Response.text658 <requests.Response.text>` attribute. Requests will first check for an659 encoding in the HTTP header, and if none is present, will use `chardet636-<http://pypi.python.org/pypi/chardet>`_ to attempt to guess the encoding.660+<https://pypi.python.org/pypi/chardet>`_ to attempt to guess the encoding.661 662 The only time Requests will not do this is if no explicit charset663 is present in the HTTP headers **and** the ``Content-Type``664 header contains ``text``. In this situation, `RFC 2616218 unmodified lines883 884 Many HTTP APIs feature Link headers. They make APIs more self describing and885 discoverable.886 863-GitHub uses these for `pagination <http://developer.github.com/v3/#pagination>`_887+GitHub uses these for `pagination <https://developer.github.com/v3/#pagination>`_888 in their API, for example::889 890 >>> url = 'https://api.github.com/users/kennethreitz/repos?page=1&per_page=10'891 >>> r = requests.head(url=url)145 unmodified linesmodified:docs/user/authentication.rst+5 added-5 removed
134 unmodified lines135 ``auth.py`` file.136 137 .. _OAuth: http://oauth.net/138 .. _requests_oauthlib: https://github.com/requests/requests-oauthlib139-.. _requests-oauthlib OAuth2 documentation: http://requests-oauthlib.readthedocs.io/en/latest/oauth2_workflow.html140-.. _Web Application Flow: http://requests-oauthlib.readthedocs.io/en/latest/oauth2_workflow.html#web-application-flow141-.. _Mobile Application Flow: http://requests-oauthlib.readthedocs.io/en/latest/oauth2_workflow.html#mobile-application-flow142-.. _Legacy Application Flow: http://requests-oauthlib.readthedocs.io/en/latest/oauth2_workflow.html#legacy-application-flow143-.. _Backend Application Flow: http://requests-oauthlib.readthedocs.io/en/latest/oauth2_workflow.html#backend-application-flow139+.. _requests-oauthlib OAuth2 documentation: https://requests-oauthlib.readthedocs.io/en/latest/oauth2_workflow.html140+.. _Web Application Flow: https://requests-oauthlib.readthedocs.io/en/latest/oauth2_workflow.html#web-application-flow141+.. _Mobile Application Flow: https://requests-oauthlib.readthedocs.io/en/latest/oauth2_workflow.html#mobile-application-flow142+.. _Legacy Application Flow: https://requests-oauthlib.readthedocs.io/en/latest/oauth2_workflow.html#legacy-application-flow143+.. _Backend Application Flow: https://requests-oauthlib.readthedocs.io/en/latest/oauth2_workflow.html#backend-application-flow144 .. _Kerberos: https://github.com/requests/requests-kerberos145 .. _NTLM: https://github.com/requests/requests-ntlm146 .. _Requests organization: https://github.com/requestsmodified:docs/user/quickstart.rst+10 added-1 removed
108 unmodified lines109 110 If you change the encoding, Requests will use the new value of ``r.encoding``111 whenever you call ``r.text``. You might want to do this in any situation where112 you can apply special logic to work out what the encoding of the content will113-be. For example, HTTP and XML have the ability to specify their encoding in113+be. For example, HTML and XML have the ability to specify their encoding in114 their body. In situations like this, you should use ``r.content`` to find the115 encoding, and then set ``r.encoding``. This will let you use ``r.text`` with116 the correct encoding.117 70 unmodified lines188 download, the above is the preferred and recommended way to retrieve the189 content. Note that ``chunk_size`` can be freely adjusted to a number that190 may better fit your use cases.191 192+.. note::193 194+ An important note about using ``Response.iter_content`` versus ``Response.raw``.195+ ``Response.iter_content`` will automatically decode the ``gzip`` and ``deflate``196+ transfer-encodings. ``Response.raw`` is a raw stream of bytes -- it does not197+ transform the response content. If you really need access to the bytes as they198+ were returned, use ``Response.raw``.199+200+201 Custom Headers202 --------------203 204 If you'd like to add HTTP headers to a request, simply pass in a ``dict`` to the75 unmodified lines280 >>> payload = {'some': 'data'}281 282 >>> r = requests.post(url, json=payload)283 284+Note, the ``json`` parameter is ignored if either ``data`` or ``files`` is passed.285 286 POST a Multipart-Encoded File287 -----------------------------288 268 unmodified linesmodified:docs/api.rst+1 added-11 removed
107 unmodified lines108 ------------------109 110 .. autoclass:: requests.codes111 112-::112+.. automodule:: requests.status_codes113 114- >>> requests.codes['temporary_redirect']115- 307114 117- >>> requests.codes.teapot118- 418119-120- >>> requests.codes['\o/']121- 200122-123-124-115 Migrating to 1.x116 ----------------117 118 This section details the main differences between 0.x and 1.x and is meant142 unmodified linesmodified:docs/conf.py+1 added-1 removed
374 unmodified lines375 376 # If false, no index is generated.377 #epub_use_index = True378 379-intersphinx_mapping = {'urllib3': ('http://urllib3.readthedocs.io/en/latest', None)}379+intersphinx_mapping = {'urllib3': ('https://urllib3.readthedocs.io/en/latest', None)}modified:requests/__init__.py+15 added
69 unmodified lines70 assert minor < 171 assert patch >= 272 73 74+def _check_cryptography(cryptography_version):75+ # cryptography < 1.3.476+ try:77+ cryptography_version = list(map(int, cryptography_version.split('.')))78+ except ValueError:79+ return80+81+ if cryptography_version < [1, 3, 4]:82+ warning = 'Old version of cryptography ({0}) may cause slowdown.'.format(cryptography_version)83+ warnings.warn(warning, RequestsDependencyWarning)84+85 # Check imported dependencies for compatibility.86 try:87 check_compatibility(urllib3.__version__, chardet.__version__)88 except (AssertionError, ValueError):4 unmodified lines93 # Attempt to enable urllib3's SNI support, if possible94 try:95 from urllib3.contrib import pyopenssl96 pyopenssl.inject_into_urllib3()97+98+ # Check cryptography version99+ from cryptography import __version__ as cryptography_version100+ _check_cryptography(cryptography_version)101 except ImportError:102 pass103 104 # urllib3's DependencyWarnings should be silenced.32 unmodified linesmodified:requests/adapters.py+10 added-5 removed
11 unmodified lines12 import socket13 14 from urllib3.poolmanager import PoolManager, proxy_from_url15 from urllib3.response import HTTPResponse16+from urllib3.util import parse_url17 from urllib3.util import Timeout as TimeoutSauce18 from urllib3.util.retry import Retry19 from urllib3.exceptions import ClosedPoolError20 from urllib3.exceptions import ConnectTimeoutError7 unmodified lines28 from urllib3.exceptions import ResponseError29 30 from .models import Response31 from .compat import urlparse, basestring31-from .utils import (DEFAULT_CA_BUNDLE_PATH, get_encoding_from_headers,32- prepend_scheme_if_needed, get_auth_from_url, urldefragauth,33- select_proxy)32+from .utils import (DEFAULT_CA_BUNDLE_PATH, extract_zipped_paths,33+ get_encoding_from_headers, prepend_scheme_if_needed,34+ get_auth_from_url, urldefragauth, select_proxy)35 from .structures import CaseInsensitiveDict36 from .cookies import extract_cookies_to_jar37 from .exceptions import (ConnectionError, ConnectTimeout, ReadTimeout, SSLError,37- ProxyError, RetryError, InvalidSchema)38+ ProxyError, RetryError, InvalidSchema, InvalidProxyURL)39 from .auth import _basic_auth_str40 41 try:42 from urllib3.contrib.socks import SOCKSProxyManager176 unmodified lines219 if verify is not True:220 cert_loc = verify221 222 if not cert_loc:222- cert_loc = DEFAULT_CA_BUNDLE_PATH223+ cert_loc = extract_zipped_paths(DEFAULT_CA_BUNDLE_PATH)224 225 if not cert_loc or not os.path.exists(cert_loc):226 raise IOError("Could not find a suitable TLS CA certificate bundle, "227 "invalid path: {0}".format(cert_loc))72 unmodified lines300 proxy = select_proxy(url, proxies)301 302 if proxy:303 proxy = prepend_scheme_if_needed(proxy, 'http')304+ proxy_url = parse_url(proxy)305+ if not proxy_url.host:306+ raise InvalidProxyURL("Please check proxy URL. It is malformed"307+ " and could be missing the host.")308 proxy_manager = self.proxy_manager_for(proxy)309 conn = proxy_manager.connection_from_url(url)310 else:311 # Only scheme should be lower case219 unmodified linesmodified:requests/exceptions.py+4 added
83 unmodified lines84 class InvalidHeader(RequestException, ValueError):85 """The header value provided was somehow invalid."""86 87 88+class InvalidProxyURL(InvalidURL):89+ """The proxy URL provided is invalid."""90+91+92 class ChunkedEncodingError(RequestException):93 """The server declared chunked encoding but sent an invalid chunk."""94 95 31 unmodified linesmodified:requests/models.py+2 added-2 removed
684 unmodified lines685 return self.iter_content(128)686 687 @property688 def ok(self):689- """Returns True if :attr:`status_code` is less than 400.689+ """Returns True if :attr:`status_code` is less than 400, False if not.690 691 This attribute checks if the status code of the response is between692 400 and 600 to see if there was a client error or a server error. If693- the status code, is between 200 and 400, this will return True. This693+ the status code is between 200 and 400, this will return True. This694 is **not** a check to see if the response code is ``200 OK``.695 """696 try:697 self.raise_for_status()251 unmodified linesmodified:requests/sessions.py+4 added-4 removed
6 unmodified lines7 This module provides a Session object to manage and persist settings across8 requests (cookies, auth, proxies).9 """10 import os11-import platform11+import sys12 import time13 from collections import Mapping14 from datetime import timedelta15 21 unmodified lines37 # formerly defined here, reexposed here for backward compatibility38 from .models import REDIRECT_STATI39 40 # Preferred clock, based on which one is more accurate on a given system.41-if platform.system() == 'Windows':42- try: # Python 3.3+41+if sys.platform == 'win32':42+ try: # Python 3.4+43 preferred_clock = time.perf_counter44 except AttributeError: # Earlier than Python 3.45 preferred_clock = time.clock46 else:648 unmodified lines695 :rtype: requests.adapters.BaseAdapter696 """697 for (prefix, adapter) in self.adapters.items():698 699- if url.lower().startswith(prefix):699+ if url.lower().startswith(prefix.lower()):700 return adapter701 702 # Nothing matches :-/703 raise InvalidSchema("No connection adapters were found for '%s'" % url)34 unmodified linesmodified:requests/status_codes.py+33 added-5 removed
1 # -*- coding: utf-8 -*-2 3+"""4+The ``codes`` object defines a mapping from common names for HTTP statuses5+to their numerical codes, accessible either as attributes or as dictionary6+items.7+8+>>> requests.codes['temporary_redirect']9+30710+>>> requests.codes.teapot11+41812+>>> requests.codes['\o/']13+20014+15+Some codes have multiple names, and both upper- and lower-case versions of16+the names are allowed. For example, ``codes.ok``, ``codes.OK``, and17+``codes.okay`` all correspond to the HTTP status code 200.18+"""19+20 from .structures import LookupDict21 22 _codes = {23 76 unmodified lines100 }101 102 codes = LookupDict(name='status_codes')103 104+def _init():87-for code, titles in _codes.items():88- for title in titles:89- setattr(codes, title, code)90- if not title.startswith(('\\', '/')):91- setattr(codes, title.upper(), code)105+ for code, titles in _codes.items():106+ for title in titles:107+ setattr(codes, title, code)108+ if not title.startswith(('\\', '/')):109+ setattr(codes, title.upper(), code)110+111+ def doc(code):112+ names = ', '.join('``%s``' % n for n in _codes[code])113+ return '* %d: %s' % (code, names)114+115+ global __doc__116+ __doc__ = (__doc__ + '\n' +117+ '\n'.join(doc(code) for code in sorted(_codes)))118+119+_init()modified:requests/utils.py+85 added-18 removed
6 unmodified lines7 This module provides utility functions that are used within Requests8 that are also useful for external consumption.9 """10 11-import cgi11 import codecs12 import collections13 import contextlib14 import io15 import os17-import platform16 import re17 import socket18 import struct19+import sys20+import tempfile21 import warnings22+import zipfile23 24 from .__version__ import __version__25 from . import certs26 # to_native_string is unused here, but imported here for backwards compatibility12 unmodified lines39 40 DEFAULT_CA_BUNDLE_PATH = certs.where()41 42 42-if platform.system() == 'Windows':43+if sys.platform == 'win32':44 # provide a proxy_bypass version on Windows without DNS lookups45 46 def proxy_bypass_registry(host):46- if is_py3:47- import winreg48- else:49- import _winreg as winreg47 try:48+ if is_py3:49+ import winreg50+ else:51+ import _winreg as winreg52+ except ImportError:53+ return False54+55+ try:56 internetSettings = winreg.OpenKey(winreg.HKEY_CURRENT_USER,57 r'Software\Microsoft\Windows\CurrentVersion\Internet Settings')58+ # ProxyEnable could be REG_SZ or REG_DWORD, normalizing it53- proxyEnable = winreg.QueryValueEx(internetSettings,54- 'ProxyEnable')[0]59+ proxyEnable = int(winreg.QueryValueEx(internetSettings,60+ 'ProxyEnable')[0])61+ # ProxyOverride is almost always a string62 proxyOverride = winreg.QueryValueEx(internetSettings,63 'ProxyOverride')[0]64 except OSError:65 return False156 unmodified lines222 name[-1] != '>'):223 return os.path.basename(name)224 225 226+def extract_zipped_paths(path):227+ """Replace nonexistant paths that look like they refer to a member of a zip228+ archive with the location of an extracted copy of the target, or else229+ just return the provided path unchanged.230+ """231+ if os.path.exists(path):232+ # this is already a valid path, no need to do anything further233+ return path234+235+ # find the first valid part of the provided path and treat that as a zip archive236+ # assume the rest of the path is the name of a member in the archive237+ archive, member = os.path.split(path)238+ while archive and not os.path.exists(archive):239+ archive, prefix = os.path.split(archive)240+ member = '/'.join([prefix, member])241+242+ if not zipfile.is_zipfile(archive):243+ return path244+245+ zip_file = zipfile.ZipFile(archive)246+ if member not in zip_file.namelist():247+ return path248+249+ # we have a valid zip archive and a valid member of that archive250+ tmp = tempfile.gettempdir()251+ extracted_path = os.path.join(tmp, *member.split('/'))252+ if not os.path.exists(extracted_path):253+ extracted_path = zip_file.extract(member, path=tmp)254+255+ return extracted_path256+257+258 def from_key_val_list(value):259 """Take an object and test to see if it can be represented as a260 dictionary. Unless it can not be represented as such, return an261 OrderedDict, e.g.,183 unmodified lines445 pragma_re.findall(content) +446 xml_re.findall(content))447 448 449+def _parse_content_type_header(header):450+ """Returns content type and parameters from given header451+452+ :param header: string453+ :return: tuple containing content type and dictionary of454+ parameters455+ """456+457+ tokens = header.split(';')458+ content_type, params = tokens[0].strip(), tokens[1:]459+ params_dict = {}460+ items_to_strip = "\"' "461+462+ for param in params:463+ param = param.strip()464+ if param:465+ key, value = param, True466+ index_of_equals = param.find("=")467+ if index_of_equals != -1:468+ key = param[:index_of_equals].strip(items_to_strip)469+ value = param[index_of_equals + 1:].strip(items_to_strip)470+ params_dict[key] = value471+ return content_type, params_dict472+473+474 def get_encoding_from_headers(headers):475 """Returns encodings from given HTTP Header Dict.476 477 :param headers: dictionary to extract encoding from.4 unmodified lines482 483 if not content_type:484 return None485 422- content_type, params = cgi.parse_header(content_type)486+ content_type, params = _parse_content_type_header(content_type)487 488 if 'charset' in params:489 return params['charset'].strip("'\"")490 211 unmodified lines702 # we're getting isn't in the no_proxy list.703 no_proxy_arg = no_proxy704 if no_proxy is None:705 no_proxy = get_proxy('no_proxy')642- netloc = urlparse(url).netloc706+ parsed = urlparse(url)707 708 if no_proxy:709 # We need to check whether we match here. We need to see if we match646- # the end of the netloc, both with and without the port.710+ # the end of the hostname, both with and without the port.711 no_proxy = (712 host for host in no_proxy.replace(' ', '').split(',') if host713 )714 651- ip = netloc.split(':')[0]652- if is_ipv4_address(ip):715+ if is_ipv4_address(parsed.hostname):716 for proxy_ip in no_proxy:717 if is_valid_cidr(proxy_ip):655- if address_in_network(ip, proxy_ip):718+ if address_in_network(parsed.hostname, proxy_ip):719 return True657- elif ip == proxy_ip:720+ elif parsed.hostname == proxy_ip:721 # If no_proxy ip was defined in plain IP notation instead of cidr notation &722 # matches the IP of the index723 return True724 else:725+ host_with_port = parsed.hostname726+ if parsed.port:727+ host_with_port += ':{0}'.format(parsed.port)728+729 for host in no_proxy:663- if netloc.endswith(host) or netloc.split(':')[0].endswith(host):730+ if parsed.hostname.endswith(host) or host_with_port.endswith(host):731 # The URL does match something in no_proxy, so we don't want732 # to apply the proxies on this URL.733 return True734 4 unmodified lines739 # exceptions we've seen, though: this call failing in other ways can reveal740 # legitimate problems.741 with set_environ('no_proxy', no_proxy_arg):742 try:676- bypass = proxy_bypass(netloc)743+ bypass = proxy_bypass(parsed.hostname)744 except (TypeError, socket.gaierror):745 bypass = False746 747 if bypass:228 unmodified linesmodified:tests/test_requests.py+52 added-1 removed
21 unmodified lines22 cookiejar_from_dict, morsel_to_cookie)23 from requests.exceptions import (24 ConnectionError, ConnectTimeout, InvalidSchema, InvalidURL,25 MissingSchema, ReadTimeout, Timeout, RetryError, TooManyRedirects,26- ProxyError, InvalidHeader, UnrewindableBodyError, SSLError)26+ ProxyError, InvalidHeader, UnrewindableBodyError, SSLError, InvalidProxyURL)27 from requests.models import PreparedRequest28 from requests.structures import CaseInsensitiveDict29 from requests.sessions import SessionRedirectMixin30 from requests.models import urlencode494 unmodified lines525 # any proxy related error (address resolution, no route to host, etc) should result in a ProxyError526 with pytest.raises(ProxyError):527 requests.get('http://localhost:1', proxies={'http': 'non-resolvable-address'})528 529+ def test_proxy_error_on_bad_url(self, httpbin, httpbin_secure):530+ with pytest.raises(InvalidProxyURL):531+ requests.get(httpbin_secure(), proxies={'https': 'http:/badproxyurl:3128'})532+533+ with pytest.raises(InvalidProxyURL):534+ requests.get(httpbin(), proxies={'http': 'http://:8080'})535+536+ with pytest.raises(InvalidProxyURL):537+ requests.get(httpbin_secure(), proxies={'https': 'https://'})538+539+ with pytest.raises(InvalidProxyURL):540+ requests.get(httpbin(), proxies={'http': 'http:///example.com:8080'})541+542 def test_basicauth_with_netrc(self, httpbin):543 auth = ('user', 'pass')544 wrong_auth = ('wronguser', 'wrongpass')545 url = httpbin('basic-auth', 'user', 'pass')817 unmodified lines1363 s2.mount('https://', HTTPAdapter())1364 assert 'http://' in s2.adapters1365 assert 'https://' in s2.adapters1366 1367+ def test_session_get_adapter_prefix_matching(self, httpbin):1368+ prefix = 'https://example.com'1369+ more_specific_prefix = prefix + '/some/path'1370+1371+ url_matching_only_prefix = prefix + '/another/path'1372+ url_matching_more_specific_prefix = more_specific_prefix + '/longer/path'1373+ url_not_matching_prefix = 'https://another.example.com/'1374+1375+ s = requests.Session()1376+ prefix_adapter = HTTPAdapter()1377+ more_specific_prefix_adapter = HTTPAdapter()1378+ s.mount(prefix, prefix_adapter)1379+ s.mount(more_specific_prefix, more_specific_prefix_adapter)1380+1381+ assert s.get_adapter(url_matching_only_prefix) is prefix_adapter1382+ assert s.get_adapter(url_matching_more_specific_prefix) is more_specific_prefix_adapter1383+ assert s.get_adapter(url_not_matching_prefix) not in (prefix_adapter, more_specific_prefix_adapter)1384+1385+ def test_session_get_adapter_prefix_matching_mixed_case(self, httpbin):1386+ mixed_case_prefix = 'hTtPs://eXamPle.CoM/MixEd_CAse_PREfix'1387+ url_matching_prefix = mixed_case_prefix + '/full_url'1388+1389+ s = requests.Session()1390+ my_adapter = HTTPAdapter()1391+ s.mount(mixed_case_prefix, my_adapter)1392+1393+ assert s.get_adapter(url_matching_prefix) is my_adapter1394+1395+ def test_session_get_adapter_prefix_matching_is_case_insensitive(self, httpbin):1396+ mixed_case_prefix = 'hTtPs://eXamPle.CoM/MixEd_CAse_PREfix'1397+ url_matching_prefix_with_different_case = 'HtTpS://exaMPLe.cOm/MiXeD_caSE_preFIX/another_url'1398+1399+ s = requests.Session()1400+ my_adapter = HTTPAdapter()1401+ s.mount(mixed_case_prefix, my_adapter)1402+1403+ assert s.get_adapter(url_matching_prefix_with_different_case) is my_adapter1404+1405 def test_header_remove_is_case_insensitive(self, httpbin):1406 # From issue #13211407 s = requests.Session()1408 s.headers['foo'] = 'bar'1032 unmodified linesmodified:tests/test_utils.py+98 added-5 removed
1 # -*- coding: utf-8 -*-2 3 import os4 import copy5+import filecmp6 from io import BytesIO7+import zipfile8+from collections import deque9 10 import pytest11 from requests import compat12 from requests.cookies import RequestsCookieJar13 from requests.structures import CaseInsensitiveDict14 from requests.utils import (12- address_in_network, dotted_netmask,13- get_auth_from_url, get_encoding_from_headers,15+ address_in_network, dotted_netmask, extract_zipped_paths,16+ get_auth_from_url, _parse_content_type_header, get_encoding_from_headers,17 get_encodings_from_content, get_environ_proxies,18 guess_filename, guess_json_utf, is_ipv4_address,19 is_valid_cidr, iter_slices, parse_dict_header,20 parse_header_links, prepend_scheme_if_needed,237 unmodified lines258 assert result == value259 assert isinstance(result, expected_type)260 261 262+class TestExtractZippedPaths:263+264+ @pytest.mark.parametrize(265+ 'path', (266+ '/',267+ __file__,268+ pytest.__file__,269+ '/etc/invalid/location',270+ ))271+ def test_unzipped_paths_unchanged(self, path):272+ assert path == extract_zipped_paths(path)273+274+ def test_zipped_paths_extracted(self, tmpdir):275+ zipped_py = tmpdir.join('test.zip')276+ with zipfile.ZipFile(zipped_py.strpath, 'w') as f:277+ f.write(__file__)278+279+ _, name = os.path.splitdrive(__file__)280+ zipped_path = os.path.join(zipped_py.strpath, name.lstrip(r'\/'))281+ extracted_path = extract_zipped_paths(zipped_path)282+283+ assert extracted_path != zipped_path284+ assert os.path.exists(extracted_path)285+ assert filecmp.cmp(extracted_path, __file__)286+287+288 class TestContentEncodingDetection:289 290 def test_none(self):291 encodings = get_encodings_from_content('')180 unmodified lines472 473 @pytest.mark.parametrize(474 'value, expected', (475 (476+ 'application/xml',477+ ('application/xml', {})478+ ),479+ (480+ 'application/json ; charset=utf-8',481+ ('application/json', {'charset': 'utf-8'})482+ ),483+ (484+ 'text/plain',485+ ('text/plain', {})486+ ),487+ (488+ 'multipart/form-data; boundary = something ; boundary2=\'something_else\' ; no_equals ',489+ ('multipart/form-data', {'boundary': 'something', 'boundary2': 'something_else', 'no_equals': True})490+ ),491+ (492+ 'multipart/form-data; boundary = something ; boundary2="something_else" ; no_equals ',493+ ('multipart/form-data', {'boundary': 'something', 'boundary2': 'something_else', 'no_equals': True})494+ ),495+ (496+ 'multipart/form-data; boundary = something ; \'boundary2=something_else\' ; no_equals ',497+ ('multipart/form-data', {'boundary': 'something', 'boundary2': 'something_else', 'no_equals': True})498+ ),499+ (500+ 'multipart/form-data; boundary = something ; "boundary2=something_else" ; no_equals ',501+ ('multipart/form-data', {'boundary': 'something', 'boundary2': 'something_else', 'no_equals': True})502+ ),503+ (504+ 'application/json ; ; ',505+ ('application/json', {})506+ )507+ ))508+def test__parse_content_type_header(value, expected):509+ assert _parse_content_type_header(value) == expected510+511+512+@pytest.mark.parametrize(513+ 'value, expected', (514+ (515 CaseInsensitiveDict(),516 None517 ),518 (94 unmodified lines613 ('http://192.168.0.1/', True),614 ('http://172.16.1.1/', True),615 ('http://172.16.1.1:5000/', True),616 ('http://localhost.localdomain:5000/v1.0/', True),617+ ('http://google.com:6000/', True),618 ('http://172.16.1.12/', False),619 ('http://172.16.1.12:5000/', False),620 ('http://google.com:5000/v1.0/', False),621 ))622 def test_should_bypass_proxies(url, expected, monkeypatch):623 """Tests for function should_bypass_proxies to check if proxy624 can be bypassed or not625 """557- monkeypatch.setenv('no_proxy', '192.168.0.0/24,127.0.0.1,localhost.localdomain,172.16.1.1')558- monkeypatch.setenv('NO_PROXY', '192.168.0.0/24,127.0.0.1,localhost.localdomain,172.16.1.1')626+ monkeypatch.setenv('no_proxy', '192.168.0.0/24,127.0.0.1,localhost.localdomain,172.16.1.1, google.com:6000')627+ monkeypatch.setenv('NO_PROXY', '192.168.0.0/24,127.0.0.1,localhost.localdomain,172.16.1.1, google.com:6000')628 assert should_bypass_proxies(url, no_proxy=None) == expected629 630 631 @pytest.mark.parametrize(632+ 'url, expected', (633+ ('http://172.16.1.1/', '172.16.1.1'),634+ ('http://172.16.1.1:5000/', '172.16.1.1'),635+ ('http://user:pass@172.16.1.1', '172.16.1.1'),636+ ('http://user:pass@172.16.1.1:5000', '172.16.1.1'),637+ ('http://hostname/', 'hostname'),638+ ('http://hostname:5000/', 'hostname'),639+ ('http://user:pass@hostname', 'hostname'),640+ ('http://user:pass@hostname:5000', 'hostname'),641+ ))642+def test_should_bypass_proxies_pass_only_hostname(url, expected, mocker):643+ """The proxy_bypass function should be called with a hostname or IP without644+ a port number or auth credentials.645+ """646+ proxy_bypass = mocker.patch('requests.utils.proxy_bypass')647+ should_bypass_proxies(url, no_proxy=None)648+ proxy_bypass.assert_called_once_with(expected)649+650+651+@pytest.mark.parametrize(652 'cookiejar', (653 compat.cookielib.CookieJar(),654 RequestsCookieJar()655 ))70 unmodified lines726 def Close(self):727 pass728 729 ie_settings = RegHandle()730+ proxyEnableValues = deque([1, "1"])731 732 def OpenKey(key, subkey):733 return ie_settings734 735 def QueryValueEx(key, value_name):736 if key is ie_settings:737 if value_name == 'ProxyEnable':648- return [1]738+ # this could be a string (REG_SZ) or a 32-bit number (REG_DWORD)739+ proxyEnableValues.rotate()740+ return [proxyEnableValues[0]]741 elif value_name == 'ProxyOverride':742 return [override]743 744 monkeypatch.setenv('http_proxy', '')2 unmodified lines747 monkeypatch.setenv('no_proxy', '')748 monkeypatch.setenv('NO_PROXY', '')749 monkeypatch.setattr(winreg, 'OpenKey', OpenKey)750 monkeypatch.setattr(winreg, 'QueryValueEx', QueryValueEx)751+ assert should_bypass_proxies(url, None) == expected752 753 754 @pytest.mark.parametrize(755 'env_name, value', (22 unmodified linesmodified:AUTHORS.rst+5 added
176 unmodified lines177 - Gary Wu (`@garywu <https://github.com/garywu>`_)178 - Ryan Pineo (`@ryanpineo <https://github.com/ryanpineo>`_)179 - Ed Morley (`@edmorley <https://github.com/edmorley>`_)180 - Matt Liu <liumatt@gmail.com> (`@mlcrazy <https://github.com/mlcrazy>`_)181+- Taylor Hoff <primdevs@protonmail.com> (`@PrimordialHelios <https://github.com/PrimordialHelios>`_)182+- Arthur Vigil (`@ahvigil <https://github.com/ahvigil>`_)183+- Nehal J Wani (`@nehaljwani <https://github.com/nehaljwani>`_)184+- Demetrios Bairaktaris (`@DemetriosBairaktaris <https://github.com/demetriosbairaktaris>`_)185+- Darren Dormer (`@ddormer <https://github.com/ddormer>`_)modified:HISTORY.rst+8 added
6 unmodified lines7 +++8 9 **Improvements**10 11+- Warn user about possible slowdown when using cryptography version < 1.3.412+- Check for invalid host in proxy URL, before forwarding request to adapter.13+14 **Bugfixes**15 16 - Parsing empty ``Link`` headers with ``parse_header_links()`` no longer return one bogus entry17+- Fixed issue where loading the default certificate bundle from a zip archive18+ would raise an ``IOError``19+- Fixed issue with unexpected ``ImportError`` on windows system which do not support ``winreg`` module20+- DNS resolution in proxy bypass no longer includes the username and password in21+ the request. This also fixes the issue of DNS queries failing on macOS.22 23 2.18.4 (2017-08-15)24 +++++++++++++++++++25 1519 unmodified linesmodified:README.rst+2 added-2 removed
75 unmodified lines76 - Streaming Downloads77 - ``.netrc`` Support78 - Chunked Requests79 80-Requests officially supports Python 2.6–2.7 & 3.3–3.7, and runs great on PyPy.80+Requests officially supports Python 2.6–2.7 & 3.4–3.6, and runs great on PyPy.81 82 Installation83 ------------84 19 unmodified lines104 #. Fork `the repository`_ on GitHub to start making your changes to the **master** branch (or branch off of it).105 #. Write a test which shows that the bug was fixed or that the feature works as expected.106 #. Send a pull request and bug the maintainer until it gets merged and published. :) Make sure to add yourself to AUTHORS_.107 108-.. _`the repository`: http://github.com/requests/requests108+.. _`the repository`: https://github.com/requests/requests109 .. _AUTHORS: https://github.com/requests/requests/blob/master/AUTHORS.rst110 .. _Contributor Friendly: https://github.com/requests/requests/issues?direction=desc&labels=Contributor+Friendly&page=1&sort=updated&state=openmodified:setup.cfg+3 added
1 [bdist_wheel]2 universal = 13+4+[metadata]5+license_file = LICENSEmodified:setup.py+2 added-1 removed
70 unmodified lines71 packages=packages,72 package_data={'': ['LICENSE', 'NOTICE'], 'requests': ['*.pem']},73 package_dir={'requests': 'requests'},74 include_package_data=True,75+ python_requires=">=2.6, !=3.0.*, !=3.1.*, !=3.2.*, !=3.3.*",76 install_requires=requires,77 license=about['__license__'],78 zip_safe=False,79 classifiers=(1 unmodified line81 'Intended Audience :: Developers',82 'Natural Language :: English',83 'License :: OSI Approved :: Apache Software License',84 'Programming Language :: Python',85+ 'Programming Language :: Python :: 2',86 'Programming Language :: Python :: 2.6',87 'Programming Language :: Python :: 2.7',88 'Programming Language :: Python :: 3',89 'Programming Language :: Python :: 3.4',9 unmodified lines99 'socks': ['PySocks>=1.5.6, !=1.5.7'],100 'socks:sys_platform == "win32" and (python_version == "2.7" or python_version == "2.6")': ['win_inet_pton'],101 },102 )101-modified:tox.ini+2 added-2 removed
1 [tox]2-envlist = py26,py27,py33,py34,py35,py362+envlist = py26,py27,py34,py35,py363 4 [testenv]5 6 commands =7 pip install -e .[socks]8- python setup.py test8+ python setup.py test