Skip to content
Myr

Merge branch 'master' into master

Before adoption: this commit came in with the history the project adopted, so no landing records it.

authored by Kenneth Reitz · committed by GitHub · parents a0d5802, ada5049 · Browse files · 28 files+217 added−365 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

28 files+217 added−365 removed

  • tests:+52 added−10 removed
  • other:+165 added−355 removed

28 files+217 added−365 removed

modified:docs/_static/custom.css+20 added-25 removed
deleted:docs/_static/native.js-131 removed
1var _native = (function () {2 var _options = {}3 var _construct = function (e) {4 var defaultOptions = {5 carbonZoneKey: '',6 fallback: '',7 ignore: 'false',8 placement: '',9 prefix: 'native',10 targetClass: 'native-ad'11 }1213 if (typeof e === 'undefined') return defaultOptions14 Object.keys(defaultOptions).forEach((key, index) => {15 if (typeof e[key] === 'undefined') {16 e[key] = defaultOptions[key]17 }18 })19 return e20 }2122 var init = function (zone, options) {23 _options = _construct(options)2425 let jsonUrl = `https://srv.buysellads.com/ads/${zone}.json?callback=_native_go`26 if (_options['placement'] !== '') {27 jsonUrl += '&segment=placement:' + _options['placement']28 }29 if (_options['ignore'] === 'true') {30 jsonUrl += '&ignore=yes'31 }3233 let srv = document.createElement('script')34 srv.src = jsonUrl35 document.getElementsByTagName('head')[0].appendChild(srv)36 }3738 var carbon = function (e) {39 let srv = document.createElement('script')40 srv.src = '//cdn.carbonads.com/carbon.js?serve=' + e['carbonZoneKey'] + '&placement=' + e['placement']41 srv.id = '_carbonads_js'4243 return srv44 }4546 var sanitize = function (ads) {47 return ads48 .filter(ad => {49 return Object.keys(ad).length > 050 })51 .filter(ad => {52 return ad.hasOwnProperty('statlink')53 })54 }5556 var pixel = function (p, timestamp) {57 let c = ''58 if (p) {59 p.split('||').forEach((pixel, index) => {60 c += `<img src="${pixel.replace('[timestamp]', timestamp)}" style="display:none;" height="0" width="0" />`61 })62 }63 return c64 }6566 var options = function () {67 return _options68 }6970 return {71 carbon: carbon,72 init: init,73 options: options,74 pixel: pixel,75 sanitize: sanitize76 }77})({})7879var _native_go = function (json) {80 let options = _native.options()81 let ads = _native.sanitize(json['ads'])82 let selectedClass = document.querySelectorAll('.' + options['targetClass'])8384 if (ads.length < 1) {85 selectedClass.forEach((className, index) => {86 let selectedTarget = document.getElementsByClassName(options['targetClass'])[index]8788 if (options['fallback'] !== '' || options['carbonZoneKey'] !== '') selectedTarget.setAttribute('data-state', 'visible')89 selectedTarget.innerHTML = options['fallback']90 if (options['carbonZoneKey'] !== '') selectedTarget.appendChild(_native.carbon(options))91 })9293 // End at this line if no ads are found, avoiding unnecessary steps94 return95 }9697 selectedClass.forEach((className, index) => {98 let selectedTarget = document.getElementsByClassName(options['targetClass'])[index]99 let adElement = selectedTarget.innerHTML100 let prefix = options['prefix']101 let ad = ads[index]102103 if (ad && className) {104 let adInnerHtml = adElement105 .replace(new RegExp('#' + prefix + '_bg_color#', 'g'), ad['backgroundColor'])106 .replace(new RegExp('#' + prefix + '_bg_color_hover#', 'g'), ad['backgroundHoverColor'])107 .replace(new RegExp('#' + prefix + '_company#', 'g'), ad['company'])108 .replace(new RegExp('#' + prefix + '_cta#', 'g'), ad['callToAction'])109 .replace(new RegExp('#' + prefix + '_cta_bg_color#', 'g'), ad['ctaBackgroundColor'])110 .replace(new RegExp('#' + prefix + '_cta_bg_color_hover#', 'g'), ad['ctaBackgroundHoverColor'])111 .replace(new RegExp('#' + prefix + '_cta_color#', 'g'), ad['ctaTextColor'])112 .replace(new RegExp('#' + prefix + '_cta_color_hover#', 'g'), ad['ctaTextColorHover'])113 .replace(new RegExp('#' + prefix + '_desc#', 'g'), ad['description'])114 .replace(new RegExp('#' + prefix + '_index#', 'g'), prefix + '-' + ad['i'])115 .replace(new RegExp('#' + prefix + '_img#', 'g'), ad['image'])116 .replace(new RegExp('#' + prefix + '_small_img#', 'g'), ad['smallImage'])117 .replace(new RegExp('#' + prefix + '_link#', 'g'), ad['statlink'])118 .replace(new RegExp('#' + prefix + '_logo#', 'g'), ad['logo'])119 .replace(new RegExp('#' + prefix + '_color#', 'g'), ad['textColor'])120 .replace(new RegExp('#' + prefix + '_color_hover#', 'g'), ad['textColorHover'])121 .replace(new RegExp('#' + prefix + '_title#', 'g'), ad['title'])122123 selectedTarget.innerHTML = null124 selectedTarget.innerHTML += adInnerHtml + _native.pixel(ad['pixel'], ad['timestamp'])125 selectedTarget.setAttribute('data-state', 'visible')126 } else {127 selectedTarget.innerHTML = null128 selectedTarget.style.display = 'none'129 }130 })131}
modified:docs/_templates/hacks.html+38 added-31 removed
55 unmodified lines
56<!-- That was not a hack. That was art. -->5758<!-- Native CPC by BuySellAds -->5960<script src="{{ pathto('_static/', 1) }}/native.js"></script>61<script>62 _native.init("CK7D62JU", {63 targetClass: 'native-js'64 });65</script>60<script type="text/javascript" src="//m.servedby-buysellads.com/monetization.js"></script>6167<div class="native-js">68 <div class="native-sponsor">Sponsored Ad by #native_company# — Learn More</div>69 <a href="#native_link#" class="native-flex">62<div id="native-ribbon">63</div>6465<script>66_bsa.init('custom', 'CK7D62JU', 'placement:pythonrequestsorg',67 {68 target: '#native-ribbon',69 template: `70<div class="native-sponsor">Sponsored by ##company## — Learn More</div>71 <a href="##link##" class="native-flex">72 <style>71 .native-js {72 background: linear-gradient(-30deg, #native_bg_color#E5, #native_bg_color#E5 45%, #native_bg_color# 45%) #fff;73 }73 #native-ribbon #_custom_ {74 background: linear-gradient(-30deg, ##backgroundColor##E5, ##backgroundColor##E5 45%, ##backgroundColor## 45%) #fff;75 }7675 .native-details,76 .native-sponsor {77 color: #native_color# !important;78 }77 .native-details,78 .native-sponsor,79 .native-bsa {80 color: ##textColor## !important;81 }8280 .native-details:hover {81 color: #native_color_hover# !important;82 }83 .native-details:hover {84 color: ##textColorHover## !important;85 }8684 .native-cta {85 color: #native_cta_color#;86 background-color: #native_cta_bg_color#;87 }87 .native-cta {88 color: ##ctaTextColor##;89 background-color: ##ctaBackgroundColor##;90 }9189 .native-cta:hover {90 color: #native_cta_color_hover;91 background-color: #native_cta_bg_color_hover#;92 }92 .native-cta:hover {93 color: ##ctaTextColorHover##;94 background-color: ##ctaBackgroundColorHover##;95 }96 </style>97 <div class="native-main">95 <img class="native-img" src="#native_logo#">98 <img class="native-img" src="##logo##">99 <div class="native-details">97 <span class="native-company">#native_title#</span>98 <span class="native-desc">#native_desc#</span>100 <span class="native-company">##title##</span>101 <span class="native-desc">##description##</span>102 </div>100 <span class="native-cta">#native_cta#</span>103 </div>104 <span class="native-cta">##callToAction##</span>105 </a>106</div>107`108 }109 );110</script>
modified:docs/_templates/sidebarintro.html+3 added-39 removed
69 unmodified lines
70 <li><a href="http://docs.python-requests.org/en/latest/community/recommended/">Recommended Packages and Extensions</a></li>7172 <p></p>7374 <li><a href="https://github.com/requests/requests">Requests @ GitHub</a></li>74 <li><a href="https://github.com/psf/requests">Requests @ GitHub</a></li>75 <li><a href="https://pypi.org/project/requests/">Requests @ PyPI</a></li>76 <li><a href="https://github.com/requests/requests/issues">Issue Tracker</a></li>76 <li><a href="https://github.com/psf/requests/issues">Issue Tracker</a></li>77 <li><a href="http://docs.python-requests.org/en/latest/community/updates/#software-updates">Release History</a></li>78</ul>7980
9 unmodified lines
90 <li><a href="http://it.python-requests.org/">Italian</a></li>91 <li><a href="http://es.python-requests.org/">Spanish</a></li>92</ul>9394<div class="native-js">95 <div class="native-sponsor">Sponsored by #native_company# — Learn More</div>96 <a href="#native_link#" class="native-flex">97 <style>98 .native-js {99 background: linear-gradient(-30deg, #native_bg_color#E5, #native_bg_color#E5 45%, #native_bg_color# 45%) #fff;100 }101102 .native-details,103 .native-sponsor,104 .native-bsa {105 color: #native_color# !important;106 }107108 .native-details:hover {109 color: #native_color_hover# !important;110 }111112 .native-cta {113 color: #native_cta_color#;114 background-color: #native_cta_bg_color#;115 }116117 .native-cta:hover {118 color: #native_cta_color_hover;119 background-color: #native_cta_bg_color_hover#;120 }121 </style>122 <div class="native-main">123 <img class="native-img" src="#native_logo#">124 <div class="native-details">125 <span class="native-company">#native_title#</span>126 <span class="native-desc">#native_desc#</span>127 </div>128 </div>129 <span class="native-cta">#native_cta#</span>130 </a>94<div id="native-ribbon">95</div>
modified:docs/community/faq.rst+2 added-1 removed
19 unmodified lines
20Custom User-Agents?21-------------------2223Requests allows you to easily override User-Agent strings, along with24any other HTTP Header.24any other HTTP Header. See `documentation about headers <http://docs.python-requests.org/en/master/user/quickstart/#custom-headers>`_.25262728Why not Httplib2?29-----------------3031Chris Adams gave an excellent summary on
58 unmodified lines
modified:docs/community/support.rst+1 added-1 removed
27 unmodified lines
28-------------2930If you notice some unexpected behaviour in Requests, or want to see support31for a new feature,32`file an issue on GitHub <https://github.com/requests/requests/issues>`_.32`file an issue on GitHub <https://github.com/psf/requests/issues>`_.333435E-mail36------
18 unmodified lines
modified:docs/community/updates.rst+1 added-1 removed
12 unmodified lines
13GitHub14------1516The best way to track the development of Requests is through17`the GitHub repo <https://github.com/requests/requests>`_.17`the GitHub repo <https://github.com/psf/requests>`_.1819Twitter20-------21
10 unmodified lines
modified:docs/dev/contributing.rst+1 added-1 removed
195 unmodified lines
196through the `GitHub issues`_, **both open and closed**, to confirm that the bug197hasn't been reported before. Duplicate bug reports are a huge drain on the time198of other contributors, and should be avoided as much as possible.199200.. _GitHub issues: https://github.com/requests/requests/issues200.. _GitHub issues: https://github.com/psf/requests/issues201202203Feature Requests204----------------
12 unmodified lines
modified:docs/dev/todo.rst+2 added-2 removed
6 unmodified lines
78#. Check for open issues or open a fresh issue to start a discussion around a bug.9 There is a Contributor Friendly tag for issues that should be ideal for people who are not very10 familiar with the codebase yet.11#. Fork `the repository <https://github.com/requests/requests>`_ on GitHub and start making your11#. Fork `the repository <https://github.com/psf/requests>`_ on GitHub and start making your12 changes to a new branch.13#. Write a test which shows that the bug was fixed.14#. Send a pull request and bug the maintainer until it gets merged and published. :)15 Make sure to add yourself to `AUTHORS <https://github.com/requests/requests/blob/master/AUTHORS.rst>`_.15 Make sure to add yourself to `AUTHORS <https://github.com/psf/requests/blob/master/AUTHORS.rst>`_.1617Feature Freeze18--------------19
45 unmodified lines
modified:docs/user/advanced.rst+6 added-6 removed
298 unmodified lines
299immediately. You can override this behaviour and defer downloading the response300body until you access the :attr:`Response.content <requests.Response.content>`301attribute with the ``stream`` parameter::302303 tarball_url = 'https://github.com/requests/requests/tarball/master'303 tarball_url = 'https://github.com/psf/requests/tarball/master'304 r = requests.get(tarball_url, stream=True)305306At this point only the response headers have been downloaded and the connection307remains open, hence allowing us to make content retrieval conditional::
371 unmodified lines
679from GitHub. Suppose we wanted commit ``a050faf`` on Requests. We would get it680like so::681682 >>> import requests683 >>> r = requests.get('https://api.github.com/repos/requests/requests/git/commits/a050faf084662f3a352dd1a941f2c7c9f886d4ad')683 >>> r = requests.get('https://api.github.com/repos/psf/requests/git/commits/a050faf084662f3a352dd1a941f2c7c9f886d4ad')684685We should confirm that GitHub responded correctly. If it has, we want to work686out what type of content it is. Do this like so::687
46 unmodified lines
734we should probably avoid making ham-handed POSTS to it. Instead, let's play735with the Issues feature of GitHub.736737This documentation was added in response to738`Issue #482 <https://github.com/requests/requests/issues/482>`_. Given that738`Issue #482 <https://github.com/psf/requests/issues/482>`_. Given that739this issue already exists, we will use it as an example. Let's start by getting it.740741::742743 >>> r = requests.get('https://api.github.com/repos/requests/requests/issues/482')743 >>> r = requests.get('https://api.github.com/repos/psf/requests/issues/482')744 >>> r.status_code745 200746747 >>> issue = json.loads(r.text)
34 unmodified lines
782783::784785 >>> body = json.dumps({u"body": u"Sounds great! I'll get right on it!"})786 >>> url = u"https://api.github.com/repos/requests/requests/issues/482/comments"786 >>> url = u"https://api.github.com/repos/psf/requests/issues/482/comments"787788 >>> r = requests.post(url=url, data=body)789 >>> r.status_code790 404
25 unmodified lines
816 >>> print(content[u"id"])817 5804413818819 >>> body = json.dumps({u"body": u"Sounds great! I'll get right on it once I feed my cat."})820 >>> url = u"https://api.github.com/repos/requests/requests/issues/comments/5804413"820 >>> url = u"https://api.github.com/repos/psf/requests/issues/comments/5804413"821822 >>> r = requests.patch(url=url, data=body, auth=auth)823 >>> r.status_code824 200
208 unmodified lines
modified:docs/user/install.rst+4 added-4 removed
23 unmodified lines
24Get the Source Code25-------------------2627Requests is actively developed on GitHub, where the code is28`always available <https://github.com/requests/requests>`_.28`always available <https://github.com/psf/requests>`_.2930You can either clone the public repository::3132 $ git clone git://github.com/requests/requests.git32 $ git clone git://github.com/psf/requests.git3334Or, download the `tarball <https://github.com/requests/requests/tarball/master>`_::34Or, download the `tarball <https://github.com/psf/requests/tarball/master>`_::3536 $ curl -OL https://github.com/requests/requests/tarball/master36 $ curl -OL https://github.com/psf/requests/tarball/master37 # optionally, zipball is also available (for Windows users).3839Once you have a copy of the source, you can embed it in your own Python40package, or install it into your site-packages easily::
3 unmodified lines
modified:docs/index.rst+2 added-2 removed
15 unmodified lines
1617.. image:: https://img.shields.io/pypi/pyversions/requests.svg18 :target: https://pypi.org/project/requests/1920.. image:: https://codecov.io/github/requests/requests/coverage.svg?branch=master21 :target: https://codecov.io/github/requests/requests20.. image:: https://codecov.io/github/psf/requests/coverage.svg?branch=master21 :target: https://codecov.io/github/psf/requests22 :alt: codecov.io2324.. image:: https://img.shields.io/badge/Say%20Thanks!-🦉-1EAEDB.svg25 :target: https://saythanks.io/to/kennethreitz
149 unmodified lines
modified:requests/adapters.py+13 added-58 removed
433 unmodified lines
434 else:435 timeout = TimeoutSauce(connect=timeout, read=timeout)436437 try:438 if not chunked:439 resp = conn.urlopen(440 method=request.method,441 url=url,442 body=request.body,443 headers=request.headers,444 redirect=False,445 assert_same_host=False,446 preload_content=False,447 decode_content=False,448 retries=self.max_retries,449 timeout=timeout450 )438 resp = conn.urlopen(439 method=request.method,440 url=url,441 body=request.body,442 headers=request.headers,443 redirect=False,444 assert_same_host=False,445 preload_content=False,446 decode_content=False,447 retries=self.max_retries,448 timeout=timeout,449 chunked=chunked450 )451452 # Send the request.453 else:454 if hasattr(conn, 'proxy_pool'):455 conn = conn.proxy_pool456457 low_conn = conn._get_conn(timeout=DEFAULT_POOL_TIMEOUT)458459 try:460 low_conn.putrequest(request.method,461 url,462 skip_accept_encoding=True)463464 for header, value in request.headers.items():465 low_conn.putheader(header, value)466467 low_conn.endheaders()468469 for i in request.body:470 low_conn.send(hex(len(i))[2:].encode('utf-8'))471 low_conn.send(b'\r\n')472 low_conn.send(i)473 low_conn.send(b'\r\n')474 low_conn.send(b'0\r\n\r\n')475476 # Receive the response from the server477 try:478 # For Python 2.7, use buffering of HTTP responses479 r = low_conn.getresponse(buffering=True)480 except TypeError:481 # For compatibility with Python 3.3+482 r = low_conn.getresponse()483484 resp = HTTPResponse.from_httplib(485 r,486 pool=conn,487 connection=low_conn,488 preload_content=False,489 decode_content=False490 )491 except:492 # If we hit any problems here, clean up the connection.493 # Then, reraise so that we can handle the actual exception.494 low_conn.close()495 raise496452 except (ProtocolError, socket.error) as err:453 raise ConnectionError(err, request=request)454455 except MaxRetryError as e:
33 unmodified lines
modified:requests/api.py+1 added-1 removed
14 unmodified lines
1516def request(method, url, **kwargs):17 """Constructs and sends a :class:`Request <Request>`.1819 :param method: method for the new :class:`Request` object: ``GET``, ``OPTIONS`, ``HEAD``, ``POST``, ``PUT``, ``PATCH``, or ``DELETE``.19 :param method: method for the new :class:`Request` object: ``GET``, ``OPTIONS``, ``HEAD``, ``POST``, ``PUT``, ``PATCH``, or ``DELETE``.20 :param url: URL for the new :class:`Request` object.21 :param params: (optional) Dictionary, list of tuples or bytes to send22 in the query string for the :class:`Request`.23 :param data: (optional) Dictionary, list of tuples, bytes, or file-like
138 unmodified lines
modified:requests/auth.py+1 added-1 removed
237 unmodified lines
238 :rtype: requests.Response239 """240241 # If response is not 4xx, do not auth242 # See https://github.com/requests/requests/issues/3772242 # See https://github.com/psf/requests/issues/3772243 if not 400 <= r.status_code < 500:244 self._thread_local.num_401_calls = 1245 return r246
59 unmodified lines
modified:requests/compat.py+2 added
41 unmodified lines
42 from urllib2 import parse_http_list43 import cookielib44 from Cookie import Morsel45 from StringIO import StringIO46 # Keep OrderedDict for backwards compatibility.47 from collections import Callable, Mapping, MutableMapping, OrderedDict484950 builtin_str = str
8 unmodified lines
59 from urllib.request import parse_http_list, getproxies, proxy_bypass, proxy_bypass_environment, getproxies_environment60 from http import cookiejar as cookielib61 from http.cookies import Morsel62 from io import StringIO63 # Keep OrderedDict for backwards compatibility.64 from collections import OrderedDict65 from collections.abc import Callable, Mapping, MutableMapping6667 builtin_str = str
5 unmodified lines
modified:requests/models.py+22 added-5 removed
10 unmodified lines
11import sys1213# Import encoding now, to avoid implicit import later.14# Implicit import within threads may cause LookupError when standard library is in a ZIP,15# such as in Embedded Python. See https://github.com/requests/requests/issues/3578.15# such as in Embedded Python. See https://github.com/psf/requests/issues/3578.16import encodings.idna1718from urllib3.fields import RequestField19from urllib3.filepost import encode_multipart_formdata
338 unmodified lines
358 #: Accept objects that have string representations.359 #: We're unable to blindly call unicode/str functions360 #: as this will include the bytestring indicator (b'')361 #: on python 3.x.362 #: https://github.com/requests/requests/pull/2238362 #: https://github.com/psf/requests/pull/2238363 if isinstance(url, bytes):364 url = url.decode('utf8')365 else:366 url = unicode(url) if is_py2 else str(url)
273 unmodified lines
640 #: The :class:`PreparedRequest <PreparedRequest>` object to which this641 #: is a response.642 self.request = None643644 #: If there was an error in the processing of content,645 #: then save the error that would return the same error when you re-appeal.646 self._error = None647648 def __enter__(self):649 return self650651 def __exit__(self, *args):
101 unmodified lines
753 if hasattr(self.raw, 'stream'):754 try:755 for chunk in self.raw.stream(chunk_size, decode_content=True):756 yield chunk757758 except ProtocolError as e:754 raise ChunkedEncodingError(e)759 self._error = ChunkedEncodingError(e)760761 except DecodeError as e:756 raise ContentDecodingError(e)762 self._error = ContentDecodingError(e)763764 except ReadTimeoutError as e:758 raise ConnectionError(e)765 self._error = ConnectionError(e)766767 finally:768 # if we had an error - throw the saved error769 if self._error:770 raise self._error771772 else:773 # Standard file-like object.774 while True:775 chunk = self.raw.read(chunk_size)
64 unmodified lines
840 self._content = None841 else:842 self._content = b''.join(self.iter_content(CONTENT_CHUNK_SIZE)) or b''843844 # if we had an error - throw the saved error845 if self._error is not None:846 raise self._error847848 self._content_consumed = True849 # don't need to release the connection; that's been handled by urllib3850 # since we exhausted the data.851 return self._content
120 unmodified lines
modified:requests/sessions.py+16 added-12 removed
9 unmodified lines
10import os11import sys12import time13from datetime import timedelta14from collections import OrderedDict1516from .auth import _basic_auth_str16from .compat import cookielib, is_py3, OrderedDict, urljoin, urlparse, Mapping17from .compat import cookielib, is_py3, urljoin, urlparse, Mapping18from .cookies import (19 cookiejar_from_dict, extract_cookies_to_jar, RequestsCookieJar, merge_cookies)20from .models import Request, PreparedRequest, DEFAULT_REDIRECT_LIMIT21from .hooks import default_hooks, dispatch_hook
72 unmodified lines
949596class SessionRedirectMixin(object):9798 def __init__(self):99 #: A list of domains that will be excluded from auth stripping100 self.trusted_domains = []101102 def get_redirect_target(self, resp):103 """Receives a Response. Returns a redirect URI or ``None``"""104 # Due to the nature of how requests processes redirects this method will105 # be called at least once upon the original response and at least twice
17 unmodified lines
123 def should_strip_auth(self, old_url, new_url):124 """Decide whether Authorization header should be removed when redirecting"""125 old_parsed = urlparse(old_url)126 new_parsed = urlparse(new_url)122 if old_parsed.hostname != new_parsed.hostname:127 if (old_parsed.hostname != new_parsed.hostname128 and new_parsed.hostname not in self.trusted_domains):129 return True130 # Special case: allow http -> https redirect when using the standard131 # ports. This isn't specified by RFC 7235, but is kept to avoid132 # breaking backwards compatibility with older versions of requests
34 unmodified lines
167 except (ChunkedEncodingError, ContentDecodingError, RuntimeError):168 resp.raw.read(decode_content=False)169170 if len(resp.history) >= self.max_redirects:165 raise TooManyRedirects('Exceeded %s redirects.' % self.max_redirects, response=resp)171 raise TooManyRedirects('Exceeded {} redirects.'.format(self.max_redirects), response=resp)172173 # Release the connection back into the pool.174 resp.close()175176 # Handle redirection without scheme (see: RFC 1808 Section 4)177 if url.startswith('//'):178 parsed_rurl = urlparse(resp.url)173 url = '%s:%s' % (to_native_string(parsed_rurl.scheme), url)179 url = ':'.join([to_native_string(parsed_rurl.scheme), url])180181 # Normalize url case and attach previous fragment if needed (RFC 7231 7.1.2)182 parsed = urlparse(url)183 if parsed.fragment == '' and previous_fragment:
13 unmodified lines
197 prepared_request.url = to_native_string(url)198199 self.rebuild_method(prepared_request, resp)200195 # https://github.com/requests/requests/issues/1084201 # https://github.com/psf/requests/issues/1084202 if resp.status_code not in (codes.temporary_redirect, codes.permanent_redirect):197 # https://github.com/requests/requests/issues/3490203 # https://github.com/psf/requests/issues/3490204 purged_headers = ('Content-Length', 'Content-Type', 'Transfer-Encoding')205 for header in purged_headers:206 prepared_request.headers.pop(header, None)207 prepared_request.body = None208209 headers = prepared_request.headers204 try:205 del headers['Cookie']206 except KeyError:207 pass210 headers.pop('Cookie', None)211212 # Extract any cookies sent on the response to the cookiejar213 # in the new request. Because we've mutated our copied prepared214 # request, use the old one that we haven't yet touched.
58 unmodified lines
273 new_auth = get_netrc_auth(url) if self.trust_env else None274 if new_auth is not None:275 prepared_request.prepare_auth(new_auth)276274 return277278 def rebuild_proxies(self, prepared_request, proxies):279 """This method re-evaluates the proxy configuration by considering the280 environment variables. If we are redirected to a URL covered by
137 unmodified lines
418 self.adapters = OrderedDict()419 self.mount('https://', HTTPAdapter())420 self.mount('http://', HTTPAdapter())421422 super().__init__()423424 def __enter__(self):425 return self426427 def __exit__(self, *args):
303 unmodified lines
731 if url.lower().startswith(prefix.lower()):732 return adapter733734 # Nothing matches :-/731 raise InvalidSchema("No connection adapters were found for '%s'" % url)735 raise InvalidSchema("No connection adapters were found for {!r}".format(url))736737 def close(self):738 """Closes all adapters and as such the session"""739 for v in self.adapters.values():
35 unmodified lines
modified:requests/structures.py+3 added-1 removed
5 unmodified lines
67Data structures that power Requests.8"""910from .compat import OrderedDict, Mapping, MutableMapping10from collections import OrderedDict1112from .compat import Mapping, MutableMapping131415class CaseInsensitiveDict(MutableMapping):16 """A case-insensitive ``dict``-like object.1718 Implements all methods and operations of
87 unmodified lines
modified:requests/utils.py+3 added-2 removed
17 unmodified lines
18import sys19import tempfile20import warnings21import zipfile22from collections import OrderedDict2324from .__version__ import __version__25from . import certs26# to_native_string is unused here, but imported here for backwards compatibility27from ._internal_utils import to_native_string28from .compat import parse_http_list as _parse_list_header29from .compat import (29 quote, urlparse, bytes, str, OrderedDict, unquote, getproxies,30 quote, urlparse, bytes, str, unquote, getproxies,31 proxy_bypass, urlunparse, basestring, integer_types, is_py3,32 proxy_bypass_environment, getproxies_environment, Mapping)33from .cookies import cookiejar_from_dict34from .structures import CaseInsensitiveDict
144 unmodified lines
179 loc = os.path.expanduser('~/{}'.format(f))180 except KeyError:181 # os.path.expanduser can fail when $HOME is undefined and182 # getpwuid fails. See https://bugs.python.org/issue20164 &182 # https://github.com/requests/requests/issues/1846183 # https://github.com/psf/requests/issues/1846184 return185186 if os.path.exists(loc):187 netrc_path = loc
795 unmodified lines
modified:tests/test_lowlevel.py+43 added-2 removed
1 unmodified line
23import pytest4import threading5import requests6from requests.exceptions import ChunkedEncodingError78from tests.testserver.server import Server, consume_socket_content910from .utils import override_environ
17 unmodified lines
28def test_digestauth_401_count_reset_on_redirect():29 """Ensure we correctly reset num_401_calls after a successful digest auth,30 followed by a 302 redirect to another digest auth prompt.3131 See https://github.com/requests/requests/issues/1979.32 See https://github.com/psf/requests/issues/1979.33 """34 text_401 = (b'HTTP/1.1 401 UNAUTHORIZED\r\n'35 b'Content-Length: 0\r\n'36 b'WWW-Authenticate: Digest nonce="6bf5d6e4da1ce66918800195d6b9130d"'
101 unmodified lines
138139def test_digestauth_only_on_4xx():140 """Ensure we only send digestauth on 4xx challenges.141141 See https://github.com/requests/requests/issues/3772.142 See https://github.com/psf/requests/issues/3772.143 """144 text_200_chal = (b'HTTP/1.1 200 OK\r\n'145 b'Content-Length: 0\r\n'146 b'WWW-Authenticate: Digest nonce="6bf5d6e4da1ce66918800195d6b9130d"'
160 unmodified lines
307 # Verify previous fragment is used and not the original.308 assert r.url == 'http://{}:{}/final-url/#relevant-section'.format(host, port)309310 close_server.set()311312313def test_response_content_retains_error():314 """Verify that accessing response.content retains an error.315316 See https://github.com/kennethreitz/requests/issues/4965317 """318319 data = "Some random stuff to read from remove server.\n"320321 def response_handler(sock):322 req = consume_socket_content(sock, timeout=0.5)323324 # Send invalid chunked data (length mismatch)325 sock.send(326 b'HTTP/1.1 200 OK\r\n'327 b'Transfer-Encoding: chunked\r\n'328 b'\r\n2\r\n42\r\n8\r\n123\r\n' # 5 bytes missing329 )330331 close_server = threading.Event()332 server = Server(response_handler, wait_to_close_event=close_server)333334 with server as (host, port):335 url = 'http://{}:{}/path'.format(host, port)336 r = requests.post(url, stream=True)337 with pytest.raises(ChunkedEncodingError):338 r.content339340 # Access the bad response data again, I would expect the same341 # error again.342343 try:344 content = r.content345 except ChunkedEncodingError:346 pass # fine, same exception347 else:348 assert False, "error response has content: {0!r}".format(content)349 close_server.set()350
modified:tests/test_requests.py+6 added-6 removed
16 unmodified lines
17from requests.adapters import HTTPAdapter18from requests.auth import HTTPDigestAuth, _basic_auth_str19from requests.compat import (20 Morsel, cookielib, getproxies, str, urlparse,21 builtin_str, OrderedDict)21 builtin_str)22from requests.cookies import (23 cookiejar_from_dict, morsel_to_cookie)24from requests.exceptions import (25 ConnectionError, ConnectTimeout, InvalidSchema, InvalidURL,
103 unmodified lines
129 request = requests.Request('GET', url, params={"a": "b"}).prepare()130 assert request.url == expected131132 def test_params_original_order_is_preserved_by_default(self):133 param_ordered_dict = OrderedDict((('z', 1), ('a', 1), ('k', 1), ('d', 1)))133 param_ordered_dict = collections.OrderedDict((('z', 1), ('a', 1), ('k', 1), ('d', 1)))134 session = requests.Session()135 request = requests.Request('GET', 'http://example.com/', params=param_ordered_dict)136 prep = session.prepare_request(request)137 assert prep.url == 'http://example.com/?z=1&a=1&k=1&d=1'
307 unmodified lines
445446 def test_headers_preserve_order(self, httpbin):447 """Preserve order when headers provided as OrderedDict."""448 ses = requests.Session()449 ses.headers = OrderedDict()449 ses.headers = collections.OrderedDict()450 ses.headers['Accept-Encoding'] = 'identity'451 ses.headers['First'] = '1'452 ses.headers['Second'] = '2'453 headers = OrderedDict([('Third', '3'), ('Fourth', '4')])453 headers = collections.OrderedDict([('Third', '3'), ('Fourth', '4')])454 headers['Fifth'] = '5'455 headers['Second'] = '222'456 req = requests.Request('GET', httpbin('get'), headers=headers)457 prep = ses.prepare_request(req)
7 unmodified lines
465466 @pytest.mark.parametrize('key', ('User-agent', 'user-agent'))467 def test_user_agent_transfers(self, httpbin, key):468469 heads = {key: 'Mozilla/5.0 (github.com/requests/requests)'}469 heads = {key: 'Mozilla/5.0 (github.com/psf/requests)'}470471 r = requests.get(httpbin('user-agent'), headers=heads)472 assert heads[key] in r.text473
1737 unmodified lines
2211 except ConnectTimeout:2212 pass22132214 def test_encoded_methods(self, httpbin):2215 """See: https://github.com/requests/requests/issues/2316"""2215 """See: https://github.com/psf/requests/issues/2316"""2216 r = requests.request(b'GET', httpbin('get'))2217 assert r.ok22182219
308 unmodified lines
modified:tests/test_utils.py+3 added-2 removed
31 unmodified lines
32 @pytest.mark.parametrize(33 'stream, value', (34 (StringIO.StringIO, 'Test'),35 (BytesIO, b'Test'),36 pytest.mark.skipif('cStringIO is None')((cStringIO, 'Test')),36 pytest.param(cStringIO, 'Test',37 marks=pytest.mark.skipif('cStringIO is None')),38 ))39 def test_io_streams(self, stream, value):40 """Ensures that we properly deal with different kinds of IO streams."""41 assert super_len(stream()) == 0
355 unmodified lines
397 'http://example.com/fiz?buz=%25ppicture',398 ),399 ))400def test_requote_uri_with_unquoted_percents(uri, expected):400 """See: https://github.com/requests/requests/issues/2356"""401 """See: https://github.com/psf/requests/issues/2356"""402 assert requote_uri(uri) == expected403404405@pytest.mark.parametrize(
378 unmodified lines
modified:.travis.yml+1 added-14 removed
1 unmodified line
2# command to install dependencies3install: "make"4# command to run tests5script:6 - |7 make test-readme6 - make test-readme7 - make ci8cache: pip9jobs:10 include:11 - stage: test13 script:14 - make test-readme15 - make ci12 python: '2.7'13 - stage: test18 script:19 - make test-readme20 - make ci14 python: '3.5'15 - stage: test23 script:24 - make test-readme25 - make ci16 python: '3.6'17 - stage: test28 script:29 - make test-readme30 - make ci18 python: '3.7'19 dist: xenial 20 - stage: coverage21 python: '3.6'
1 unmodified line
modified:AUTHORS.rst+2 added
189 unmodified lines
190- Rajiv Mayani (`@mayani <https://github.com/mayani>`_)191- Antti Kaihola (`@akaihola <https://github.com/akaihola>`_)192- "Dull Bananas" <dull.bananas0@gmail.com> (`@dullbananas <https://github.com/dullbananas>`_)193- Alessio Izzo (`@aless10 <https://github.com/aless10>`_)194- Belavin Denis (`@luckydenis <https://github.com/luckydenis>`_)195- Dull Bananas <dull.bananas0@gmail.com> (`@dullbananas <https://github.com/dullbananas>`_)
modified:HISTORY.md+9 added-9 removed
791 unmodified lines
792793- Unicode URL improvements for Python 2.794- Re-order JSON param for backwards compat.795- Automatically defrag authentication schemes from host/pass URIs.796 ([\#2249](https://github.com/requests/requests/issues/2249))796 ([\#2249](https://github.com/psf/requests/issues/2249))7977982.4.2 (2014-10-05)799------------------800801**Improvements**802803- FINALLY! Add json parameter for uploads!804 ([\#2258](https://github.com/requests/requests/pull/2258))804 ([\#2258](https://github.com/psf/requests/pull/2258))805- Support for bytestring URLs on Python 3.x806 ([\#2238](https://github.com/requests/requests/pull/2238))806 ([\#2238](https://github.com/psf/requests/pull/2238))807808**Bugfixes**809810- Avoid getting stuck in a loop811 ([\#2244](https://github.com/requests/requests/pull/2244))811 ([\#2244](https://github.com/psf/requests/pull/2244))812- Multiple calls to iter\* fail with unhelpful error.813 ([\#2240](https://github.com/requests/requests/issues/2240),814 [\#2241](https://github.com/requests/requests/issues/2241))813 ([\#2240](https://github.com/psf/requests/issues/2240),814 [\#2241](https://github.com/psf/requests/issues/2241))815816**Documentation**817818- Correct redirection introduction819 ([\#2245](https://github.com/requests/requests/pull/2245/))819 ([\#2245](https://github.com/psf/requests/pull/2245/))820- Added example of how to send multiple files in one request.821 ([\#2227](https://github.com/requests/requests/pull/2227/))821 ([\#2227](https://github.com/psf/requests/pull/2227/))822- Clarify how to pass a custom set of CAs823 ([\#2248](https://github.com/requests/requests/pull/2248/))823 ([\#2248](https://github.com/psf/requests/pull/2248/))8248252.4.1 (2014-09-09)826------------------827
823 unmodified lines
modified:README.md+7 added-7 removed
2 unmodified lines
34[![image](https://img.shields.io/pypi/v/requests.svg)](https://pypi.org/project/requests/)5[![image](https://img.shields.io/pypi/l/requests.svg)](https://pypi.org/project/requests/)6[![image](https://img.shields.io/pypi/pyversions/requests.svg)](https://pypi.org/project/requests/)7[![codecov.io](https://codecov.io/github/requests/requests/coverage.svg?branch=master)](https://codecov.io/github/requests/requests)8[![image](https://img.shields.io/github/contributors/requests/requests.svg)](https://github.com/requests/requests/graphs/contributors)7[![codecov.io](https://codecov.io/github/psf/requests/coverage.svg?branch=master)](https://codecov.io/github/psf/requests)8[![image](https://img.shields.io/github/contributors/psf/requests.svg)](https://github.com/psf/requests/graphs/contributors)9[![image](https://img.shields.io/badge/Say%20Thanks-!-1EAEDB.svg)](https://saythanks.io/to/kennethreitz)1011Requests is the only *Non-GMO* HTTP library for Python, safe for human12consumption.
18 unmodified lines
31```3233See [the similar code, sans Requests](https://gist.github.com/973705).3435[![image](https://raw.githubusercontent.com/requests/requests/master/docs/_static/requests-logo-small.png)](http://docs.python-requests.org/)35[![image](https://raw.githubusercontent.com/psf/requests/master/docs/_static/requests-logo-small.png)](http://docs.python-requests.org/)3637Requests allows you to send *organic, grass-fed* HTTP/1.1 requests,38without the need for manual labor. There's no need to manually add query39strings to your URLs, or to form-encode your POST data. Keep-alive and40HTTP connection pooling are 100% automatic, thanks to41[urllib3](https://github.com/shazow/urllib3).4243Besides, all the cool kids are doing it. Requests is one of the most44downloaded Python packages of all time, pulling in over 11,000,00044downloaded Python packages of all time, pulling in over 50,000,00045downloads every month. You don't want to be left out!4647Feature Support48---------------
43 unmodified lines
92931. Become more familiar with the project by reading our [Contributor's Guide](http://docs.python-requests.org/en/latest/dev/contributing/) and our [development philosophy](http://docs.python-requests.org/en/latest/dev/philosophy/).942. Check for open issues or open a fresh issue to start a discussion95 around a feature idea or a bug. There is a [Contributor96 Friendly](https://github.com/requests/requests/issues?direction=desc&labels=Contributor+Friendly&page=1&sort=updated&state=open)96 Friendly](https://github.com/psf/requests/issues?direction=desc&labels=Contributor+Friendly&page=1&sort=updated&state=open)97 tag for issues that should be ideal for people who are not very98 familiar with the codebase yet.993. Fork [the repository](https://github.com/requests/requests) on993. Fork [the repository](https://github.com/psf/requests) on100 GitHub to start making your changes to the **master** branch (or101 branch off of it).1024. Write a test which shows that the bug was fixed or that the feature103 works as expected.1045. Send a [pull request](https://help.github.com/en/articles/creating-a-pull-request-from-a-fork) and bug the maintainer until it gets merged and105 published. :) Make sure to add yourself to106 [AUTHORS](https://github.com/requests/requests/blob/master/AUTHORS.rst).106 [AUTHORS](https://github.com/psf/requests/blob/master/AUTHORS.rst).107
modified:setup.py+5 added-1 removed
52 unmodified lines
53 'pytest-cov',54 'pytest-mock',55 'pytest-xdist',56 'PySocks>=1.5.6, !=1.5.7',57 'pytest>=2.8.0'57 'pytest>=3'58]5960about = {}61with open(os.path.join(here, 'requests', '__version__.py'), 'r', 'utf-8') as f:
42 unmodified lines
104 'security': ['pyOpenSSL >= 0.14', 'cryptography>=1.3.4', 'idna>=2.0.0'],105 'socks': ['PySocks>=1.5.6, !=1.5.7'],106 'socks:sys_platform == "win32" and python_version == "2.7"': ['win_inet_pton'],107 },108 project_urls={109 'Documentation': 'http://docs.python-requests.org',110 'Source': 'https://github.com/kennethreitz/requests',111 },112)