Merge branch 'master' into master
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by David Poole · committed by GitHub · parents efacb9e, 4ea09e4 · Browse files · 26 files·+251 added−83 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
26 files+251 added−83 removed
- tests:+143 added−3 removed
- other:+108 added−80 removed
Provenance
- Commit
85ec7d7- Tree
7fd8e7c- Author
David Poole <testcluster@gmail.com>- Committer
GitHub <noreply@github.com>- Parent 1
efacb9e- Parent 2
4ea09e4
26 files changed+251 added−83 removed
modified:docs/_templates/sidebarintro.html+7 added-7 removed
3 unmodified lines45678891011126 unmodified lines192021222323242526272829303132333334353637389 unmodified lines48495051515253525354555657588 unmodified lines67686970703 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><p><a href="http://tinyletter.com/kennethreitz">Join Mailing List</a>.</p><h3>Other Projects</h3>
<p>More <a href="http://kennethreitz.org/">Kenneth Reitz</a> projects:</p><ul> <li><a href="http://edmsynths.com/">edmsynths.com</a></li> <li><a href="http://html.python-requests.org/">Requests-HTML</a></li> <li><a href="http://howtopython.org/">howtopython.org</a></li> <li><a href="http://pipenv.org/">pipenv</a></li> <li><a href="http://pep8.org/">pep8.org</a></li> <li><a href="http://httpbin.org/">httpbin.org</a></li> <li><a href="http://python-guide.org">The Python Guide</a></li>9 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>
8 unmodified lines <li><a href="http://pt.python-requests.org/">Portuguese</a></li> <li><a href="http://it.python-requests.org/">Italian</a></li> <li><a href="http://es.python-requests.org/">Spanish</a></li></ul>
modified:docs/_templates/sidebarlogo.html+4 added-4 removed
2 unmodified lines34567789101112 unmodified lines2425262728282930313233343536373838394041424315 unmodified lines59606162622 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>
<h3>Other Projects</h3>
<p>More <a href="http://kennethreitz.org/">Kenneth Reitz</a> projects:</p><ul> <li><a href="http://edmsynths.com/">edmsynths.com</a></li> <li><a href="http://html.python-requests.org/">Requests-HTML</a></li> <li><a href="http://howtopython.org/">howtopython.org</a></li> <li><a href="http://pipenv.org/">pipenv</a></li> <li><a href="http://pep8.org/">pep8.org</a></li> <li><a href="http://httpbin.org/">httpbin.org</a></li> <li><a href="http://python-guide.org">The Python Guide</a></li>15 unmodified lines <li><a href="http://pt.python-requests.org/">Portuguese</a></li> <li><a href="http://it.python-requests.org/">Italian</a></li> <li><a href="http://es.python-requests.org/">Spanish</a></li></ul>
modified: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+2 added-5 removed
13 unmodified lines14 `Certifi`_ is a carefully curated collection of Root Certificates for15 validating the trustworthiness of SSL certificates while verifying the16 identity of TLS hosts. It has been extracted from the Requests project.17 18-.. _Certifi: http://certifi.io/en/latest/18+.. _Certifi: https://github.com/certifi/python-certifi19 20 CacheControl21 ------------22 10 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 ----------------19 unmodified lines61 `Betamax`_ records your HTTP interactions so the NSA does not have to.62 A VCR imitation designed only for Python-Requests.63 64 .. _betamax: https://github.com/sigmavirus24/betamax65-66-67-modified:docs/community/release-process.rst+8 added-9 removed
17 unmodified lines18 Breaking changes are changes that break backwards compatibility with prior19 versions. If the project were to change the ``text`` attribute on a20 ``Response`` object to a method, that would only happen in a Major release.21 22-Major releases may also include miscellaneous bug fixes and upgrades to23-vendored packages. The core developers of Requests are committed to providing24-a good user experience. This means we're also committed to preserving25-backwards compatibility as much as possible. Major releases will be infrequent26-and will need strong justifications before they are considered.22+Major releases may also include miscellaneous bug fixes. The core developers of23+Requests are committed to providing a good user experience. This means we're24+also committed to preserving backwards compatibility as much as possible. Major25+releases will be infrequent and will need strong justifications before they are26+considered.27 28 Minor Releases29 --------------30 31-A minor release will not include breaking changes but may include32-miscellaneous bug fixes and upgrades to vendored packages. If the previous33-version of Requests released was ``v10.2.7`` a minor release would be34-versioned as ``v10.3.0``.31+A minor release will not include breaking changes but may include miscellaneous32+bug fixes. If the previous version of Requests released was ``v10.2.7`` a minor33+release would be versioned as ``v10.3.0``.34 35 Minor releases will be backwards compatible with releases that have the same36 major version number. In other words, all versions that would start with37 ``v10.`` should be compatible with each other.18 unmodified linesmodified:docs/community/updates.rst-1 removed
27 unmodified lines28 Release and Version History29 ===========================30 31 .. include:: ../../HISTORY.rst32-modified:docs/dev/todo.rst+1 added-2 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/65-64+.. _Requests-Toolbelt: https://toolbelt.readthedocs.io/modified:docs/user/advanced.rst+16 added-17 removed
194 unmodified lines195 As a result an ``SSL: CERTIFICATE_VERIFY_FAILED`` is thrown.196 You can get around this behaviour by explicity merging the environment settings into your session::197 198 from requests import Request, Session199- 199+200 s = Session()201 req = Request('GET', url)202- 202+203 prepped = s.prepare_request(req)204- 204+205 # Merge environment settings into session206 settings = s.merge_environment_settings(prepped.url, None, None, None, None)207 resp = s.send(prepped, **settings)208- 208+209 print(resp.status_code)210- 210+211 .. _verification:212 213 SSL Cert Verification214 ---------------------58 unmodified lines273 274 CA Certificates275 ---------------276 277-By default, Requests bundles a set of root CAs that it trusts, sourced from the278-`Mozilla trust store`_. However, these are only updated once for each Requests279-version. This means that if you pin a Requests version your certificates can280-become extremely out of date.277+Requests uses certificates from the package `certifi`_. This allows for users278+to update their trusted certificates without changing the version of Requests.279 282-From Requests version 2.4.0 onwards, Requests will attempt to use certificates283-from `certifi`_ if it is present on the system. This allows for users to update284-their trusted certificates without having to change the code that runs on their285-system.280+Before version 2.16, Requests bundled a set of root CAs that it trusted,281+sourced from the `Mozilla trust store`_. The certificates were only updated282+once for each Requests version. When ``certifi`` was not installed, this led to283+extremely out-of-date certificate bundles when using significantly older284+versions of Requests.285 286 For the sake of security we recommend upgrading certifi frequently!287 288 .. _HTTP persistent connection: https://en.wikipedia.org/wiki/HTTP_persistent_connection290-.. _connection pooling: http://urllib3.readthedocs.io/en/latest/reference/index.html#module-urllib3.connectionpool289+.. _connection pooling: https://urllib3.readthedocs.io/en/latest/reference/index.html#module-urllib3.connectionpool290 .. _certifi: http://certifi.io/291 .. _Mozilla trust store: https://hg.mozilla.org/mozilla-central/raw-file/tip/security/nss/lib/ckfw/builtins/certdata.txt292 293 .. _body-content-workflow:361 unmodified lines655 When you receive a response, Requests makes a guess at the encoding to656 use for decoding the response when you access the :attr:`Response.text657 <requests.Response.text>` attribute. Requests will first check for an658 encoding in the HTTP header, and if none is present, will use `chardet660-<http://pypi.python.org/pypi/chardet>`_ to attempt to guess the encoding.659+<https://pypi.python.org/pypi/chardet>`_ to attempt to guess the encoding.660 661 The only time Requests will not do this is if no explicit charset662 is present in the HTTP headers **and** the ``Content-Type``663 header contains ``text``. In this situation, `RFC 2616218 unmodified lines882 883 Many HTTP APIs feature Link headers. They make APIs more self describing and884 discoverable.885 887-GitHub uses these for `pagination <http://developer.github.com/v3/#pagination>`_886+GitHub uses these for `pagination <https://developer.github.com/v3/#pagination>`_887 in their API, for example::888 889 >>> url = 'https://api.github.com/users/kennethreitz/repos?page=1&per_page=10'890 >>> r = requests.head(url=url)58 unmodified lines949 passed-through to `urllib3`. We'll make a Transport Adapter that instructs the950 library to use SSLv3::951 952 import ssl953+ from urllib3.poolmanager import PoolManager954 955 from requests.adapters import HTTPAdapter956- from requests.packages.urllib3.poolmanager import PoolManager956 957 958 class Ssl3HttpAdapter(HTTPAdapter):959 """"Transport adapter" that allows us to use SSLv3."""76 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+1 added-1 removed
169 unmodified lines170 171 >>> r = requests.get('https://api.github.com/events', stream=True)172 173 >>> r.raw174- <requests.packages.urllib3.response.HTTPResponse object at 0x101194810>174+ <urllib3.response.HTTPResponse object at 0x101194810>175 176 >>> r.raw.read(10)177 '\x1f\x8b\x08\x00\x00\x00\x00\x00\x00\x03'178 378 unmodified linesmodified:docs/api.rst+1 added-1 removed
179 unmodified lines180 HTTPConnection.debuglevel = 1181 182 logging.basicConfig() # you need to initialize logging, otherwise you will not see anything from requests183 logging.getLogger().setLevel(logging.DEBUG)184- requests_log = logging.getLogger("requests.packages.urllib3")184+ requests_log = logging.getLogger("urllib3")185 requests_log.setLevel(logging.DEBUG)186 requests_log.propagate = True187 188 requests.get('http://httpbin.org/headers')72 unmodified linesmodified:docs/conf.py+2 added-2 removed
56 unmodified lines57 master_doc = 'index'58 59 # General information about the project.60 project = u'Requests'61-copyright = u'MMXVII. A <a href="http://kennethreitz.com/pages/open-projects.html">Kenneth Reitz</a> Project'61+copyright = u'MMXVIII. A <a href="http://kennethreitz.com/pages/open-projects.html">Kenneth Reitz</a> Project'62 author = u'Kenneth Reitz'63 64 # The version info for the project you're documenting, acts as replacement for65 # |version| and |release|, also used in various other places throughout the309 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:docs/index.rst+3 added-3 removed
28 unmodified lines29 consumption.30 31 .. note:: The use of **Python 3** is *highly* preferred over Python 2. Consider upgrading your applications and infrastructure if you find yourself *still* using Python 2 in production today. If you are using Python 3, congratulations — you are indeed a person of excellent taste.32 —*Kenneth Reitz*33- 34- 33+34+35 -------------------36 37 **Behold, the power of Requests**::38 19 unmodified lines58 59 User Testimonials60 -----------------61 62-Twitter, Spotify, Microsoft, Amazon, Lyft, BuzzFeed, Reddit, The NSA, Her Majesty's Government, Google, Twilio, Runscope, Mozilla, Heroku,62+Nike, Twitter, Spotify, Microsoft, Amazon, Lyft, BuzzFeed, Reddit, The NSA, Her Majesty's Government, Google, Twilio, Runscope, Mozilla, Heroku,63 PayPal, NPR, Obama for America, Transifex, Native Instruments, The Washington64 Post, SoundCloud, Kippt, Sony, and Federal U.S.65 Institutions that prefer to be unnamed claim to use Requests internally.66 105 unmodified linesmodified:requests/adapters.py+1 added-1 removed
409 unmodified lines410 conn = self.get_connection(request.url, proxies)411 412 self.cert_verify(conn, request.url, verify, cert)413 url = self.request_url(request, proxies)414- self.add_headers(request)414+ self.add_headers(request, stream=stream, timeout=timeout, verify=verify, cert=cert, proxies=proxies)415 416 chunked = not (request.body is None or 'Content-Length' in request.headers)417 418 if isinstance(timeout, tuple):112 unmodified linesmodified:requests/help.py+1 added-1 removed
11 unmodified lines12 13 from . import __version__ as requests_version14 15 try:16- from .packages.urllib3.contrib import pyopenssl16+ from urllib3.contrib import pyopenssl17 except ImportError:18 pyopenssl = None19 OpenSSL = None20 cryptography = None100 unmodified linesmodified:requests/sessions.py+6 added-1 removed
121 unmodified lines122 123 hist = [] # keep track of history124 125 url = self.get_redirect_target(resp)126+ previous_fragment = urlparse(req.url).fragment127 while url:128 prepared_request = req.copy()129 130 # Update history and keep track of redirects.16 unmodified lines147 if url.startswith('//'):148 parsed_rurl = urlparse(resp.url)149 url = '%s:%s' % (to_native_string(parsed_rurl.scheme), url)150 150- # The scheme should be lower case...151+ # Normalize url case and attach previous fragment if needed (RFC 7231 7.1.2)152 parsed = urlparse(url)153+ if parsed.fragment == '' and previous_fragment:154+ parsed = parsed._replace(fragment=previous_fragment)155+ elif parsed.fragment:156+ previous_fragment = parsed.fragment157 url = parsed.geturl()158 159 # Facilitate relative 'location' headers, as allowed by RFC 7231.160 # (e.g. '/path/to/resource' instead of 'http://domain.tld/path/to/resource')582 unmodified linesmodified:requests/utils.py+38 added-11 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 io208 unmodified lines223 return os.path.basename(name)224 225 226 def extract_zipped_paths(path):228- """Replace nonexistant paths that look like they refer to a member of a zip227+ """Replace nonexistent 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):213 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 462- 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')682- 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 match686- # 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 691- ip = netloc.split(':')[0]692- 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):695- if address_in_network(ip, proxy_ip):718+ if address_in_network(parsed.hostname, proxy_ip):719 return True697- 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:703- 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:716- 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_lowlevel.py+72 added
233 unmodified lines234 assert redirect_request[0].startswith(b'GET /' + expected_path + b' HTTP/1.1')235 assert r.url == u'{0}/{1}'.format(url, expected_path.decode('ascii'))236 237 close_server.set()238+239+def test_fragment_not_sent_with_request():240+ """Verify that the fragment portion of a URI isn't sent to the server."""241+ def response_handler(sock):242+ req = consume_socket_content(sock, timeout=0.5)243+ sock.send(244+ b'HTTP/1.1 200 OK\r\n'245+ b'Content-Length: '+bytes(len(req))+b'\r\n'246+ b'\r\n'+req247+ )248+249+ close_server = threading.Event()250+ server = Server(response_handler, wait_to_close_event=close_server)251+252+ with server as (host, port):253+ url = 'http://{0}:{1}/path/to/thing/#view=edit&token=hunter2'.format(host, port)254+ r = requests.get(url)255+ raw_request = r.content256+257+ assert r.status_code == 200258+ headers, body = raw_request.split(b'\r\n\r\n', 1)259+ status_line, headers = headers.split(b'\r\n', 1)260+261+ assert status_line == b'GET /path/to/thing/ HTTP/1.1'262+ for frag in (b'view', b'edit', b'token', b'hunter2'):263+ assert frag not in headers264+ assert frag not in body265+266+ close_server.set()267+268+def test_fragment_update_on_redirect():269+ """Verify we only append previous fragment if one doesn't exist on new270+ location. If a new fragment is encounterd in a Location header, it should271+ be added to all subsequent requests.272+ """273+274+ def response_handler(sock):275+ consume_socket_content(sock, timeout=0.5)276+ sock.send(277+ b'HTTP/1.1 302 FOUND\r\n'278+ b'Content-Length: 0\r\n'279+ b'Location: /get#relevant-section\r\n\r\n'280+ )281+ consume_socket_content(sock, timeout=0.5)282+ sock.send(283+ b'HTTP/1.1 302 FOUND\r\n'284+ b'Content-Length: 0\r\n'285+ b'Location: /final-url/\r\n\r\n'286+ )287+ consume_socket_content(sock, timeout=0.5)288+ sock.send(289+ b'HTTP/1.1 200 OK\r\n\r\n'290+ )291+292+ close_server = threading.Event()293+ server = Server(response_handler, wait_to_close_event=close_server)294+295+ with server as (host, port):296+ url = 'http://{0}:{1}/path/to/thing/#view=edit&token=hunter2'.format(host, port)297+ r = requests.get(url)298+ raw_request = r.content299+300+ assert r.status_code == 200301+ assert len(r.history) == 2302+ assert r.history[0].request.url == url303+304+ # Verify we haven't overwritten the location with our previous fragment.305+ assert r.history[1].request.url == 'http://{0}:{1}/get#relevant-section'.format(host, port)306+ # Verify previous fragment is used and not the original.307+ assert r.url == 'http://{0}:{1}/final-url/#relevant-section'.format(host, port)308+309+ close_server.set()modified:tests/test_requests.py+8 added
294 unmodified lines295 assert next_resp.request.body is None296 for header in purged_headers:297 assert header not in next_resp.request.headers298 299+ def test_fragment_maintained_on_redirect(self, httpbin):300+ fragment = "#view=edit&token=hunter2"301+ r = requests.get(httpbin('redirect-to?url=get')+fragment)302+303+ assert len(r.history) > 0304+ assert r.history[0].request.url == httpbin('redirect-to?url=get')+fragment305+ assert r.url == httpbin('get')+fragment306+307 def test_HTTP_200_OK_GET_WITH_PARAMS(self, httpbin):308 heads = {'User-agent': 'Mozilla/5.0'}309 310 r = requests.get(httpbin('user-agent'), headers=heads)2149 unmodified linesmodified:tests/test_utils.py+63 added-3 removed
11 unmodified lines12 from requests.cookies import RequestsCookieJar13 from requests.structures import CaseInsensitiveDict14 from requests.utils import (15 address_in_network, dotted_netmask, extract_zipped_paths,16- get_auth_from_url, get_encoding_from_headers,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,451 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 """586- monkeypatch.setenv('no_proxy', '192.168.0.0/24,127.0.0.1,localhost.localdomain,172.16.1.1')587- 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 ))122 unmodified linesmodified:.travis.yml+1 added-3 removed
4 unmodified lines5 - "2.7"6 - "3.4"7 - "3.5"8 - "3.6"9- # - "3.7-dev"9+ - "3.7-dev"10 # - "pypy" -- appears to hang11 # - "pypy3"12 # command to install dependencies13 install: "make"12 unmodified lines26 - make ci27 - stage: coverage28 python: 3.629 script: codecov30-31-modified:AUTHORS.rst+2 added
179 unmodified lines180 - 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+4 added-2 removed
8 unmodified lines9 **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+- Fragments are now properly maintained across redirects. (RFC7231 7.1.2)14 15 **Bugfixes**16 17 - Parsing empty ``Link`` headers with ``parse_header_links()`` no longer return one bogus entry18 - Fixed issue where loading the default certificate bundle from a zip archive19 would raise an ``IOError``20 - Fixed issue with unexpected ``ImportError`` on windows system which do not support ``winreg`` module21+- DNS resolution in proxy bypass no longer includes the username and password in22+ the request. This also fixes the issue of DNS queries failing on macOS.23 21-24 2.18.4 (2017-08-15)25 +++++++++++++++++++26 27 **Improvements**102 unmodified lines130 +++++++++++++++++++131 132 - Further restored the ``requests.packages`` namespace for compatibility reasons.133 132-No code modification (noted below) should be neccessary any longer.134+No code modification (noted below) should be necessary any longer.135 136 2.16.1 (2017-05-27)137 +++++++++++++++++++138 1407 unmodified linesmodified:README.rst+1 added-1 removed
103 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.py+1 added
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=(23 unmodified linesmodified: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