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
Provenance
- Commit
df918c0- Tree
d1ca3a3- Author
Kenneth Reitz <me@kennethreitz.org>- Committer
GitHub <noreply@github.com>- Parent 1
a0d5802- Parent 2
ada5049
28 files changed+217 added−365 removed
modified:docs/_static/custom.css+20 added-25 removed
48 unmodified lines4950515253545556575853545556575859606162636465666566676869707172737475676869707111 unmodified lines83848586958788899091929394103959697989910010110211011111211310310410510616 unmodified lines12312412512612712812913013115 unmodified lines14714814915015115215315415515615715815916016116216316416516616717617716816917017117217317417517617748 unmodified lines
/* Native CPC by BuySellAds */
.native-js { visibility: hidden; font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Oxygen-Sans, Ubuntu, Cantarell, "Helvetica Neue", Helvetica, Arial, sans-serif; opacity: 0;#native-ribbon #_custom_ { position: fixed; right: 0; bottom: 0; left: 0; box-shadow: 0 -1px 4px 1px hsla(0, 0%, 0%, .15); font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Oxygen-Sans, Ubuntu, Cantarell, "Helvetica Neue", Helvetica, Arial, sans-serif; transition: all .25s ease-in-out; transform: translateY(calc(100% - 35px));
flex-flow: column nowrap;}
.native-js[data-state=visible] { position: fixed; bottom: 0; left: 0; right: 0; visibility: visible; box-shadow: 0 -1px 4px 1px hsla(0, 0%, 0%, .15); opacity: 1;}
.native-js[data-state=visible]:hover {#native-ribbon #_custom_:hover { transform: translateY(0);}
.native-img {11 unmodified lines transition: all .3s ease-in-out; transform-origin: left;}
.native-js[data-state=visible]:hover .native-sponsor {#native-ribbon #_custom_:hover .native-sponsor { margin: 0 20px; opacity: 0; transform: scaleY(0);}
.native-flex { display: flex; padding: 0 20px 30px; padding: 10px 20px 25px; text-decoration: none;
flex-flow: row nowrap; justify-content: center; align-items: center;}
.native-flex:hover { text-decoration: none;}
.native-main { display: flex;
flex-flow: row nowrap;16 unmodified lines
.native-desc { letter-spacing: 1px; font-weight: 300; font-size: 14px; line-height: 1.4;}
.native-cta {15 unmodified lines}
@media only screen and (min-width: 320px) and (max-width: 759px) { .native-flex { padding: 5px 5px 15px; flex-direction: column;
flex-wrap: wrap; }
.native-img { margin: 0; display: none; }
.native-details { margin: 0; }
.native-main { flex-direction: column; margin-bottom: 20px; text-align: center; text-align: left;
flex-wrap: wrap; align-content: center; }
.native-cta { display: none; }}deleted:docs/_static/native.js-131 removed
1-var _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- }12-13- 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- }21-22- var init = function (zone, options) {23- _options = _construct(options)24-25- 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- }32-33- let srv = document.createElement('script')34- srv.src = jsonUrl35- document.getElementsByTagName('head')[0].appendChild(srv)36- }37-38- 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'42-43- return srv44- }45-46- 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- }55-56- 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- }65-66- var options = function () {67- return _options68- }69-70- return {71- carbon: carbon,72- init: init,73- options: options,74- pixel: pixel,75- sanitize: sanitize76- }77-})({})78-79-var _native_go = function (json) {80- let options = _native.options()81- let ads = _native.sanitize(json['ads'])82- let selectedClass = document.querySelectorAll('.' + options['targetClass'])83-84- if (ads.length < 1) {85- selectedClass.forEach((className, index) => {86- let selectedTarget = document.getElementsByClassName(options['targetClass'])[index]87-88- 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- })92-93- // End at this line if no ads are found, avoiding unnecessary steps94- return95- }96-97- 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]102-103- 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'])122-123- 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 lines56 <!-- That was not a hack. That was art. -->57 58 <!-- Native CPC by BuySellAds -->59 60-<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>61 67-<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>64+65+<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+ }76 75- .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+ }82 80- .native-details:hover {81- color: #native_color_hover# !important;82- }83+ .native-details:hover {84+ color: ##textColorHover## !important;85+ }86 84- .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+ }91 89- .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 lines70 <li><a href="http://docs.python-requests.org/en/latest/community/recommended/">Recommended Packages and Extensions</a></li>71 72 <p></p>73 74- <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>79 80 9 unmodified lines90 <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>93 94-<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- }101-102- .native-details,103- .native-sponsor,104- .native-bsa {105- color: #native_color# !important;106- }107-108- .native-details:hover {109- color: #native_color_hover# !important;110- }111-112- .native-cta {113- color: #native_cta_color#;114- background-color: #native_cta_bg_color#;115- }116-117- .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 lines20 Custom User-Agents?21 -------------------22 23 Requests allows you to easily override User-Agent strings, along with24-any other HTTP Header.24+any other HTTP Header. See `documentation about headers <http://docs.python-requests.org/en/master/user/quickstart/#custom-headers>`_.25 26 27+28 Why not Httplib2?29 -----------------30 31 Chris Adams gave an excellent summary on58 unmodified linesmodified:docs/community/support.rst+1 added-1 removed
27 unmodified lines28 -------------29 30 If you notice some unexpected behaviour in Requests, or want to see support31 for 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>`_.33 34 35 E-mail36 ------18 unmodified linesmodified:docs/community/updates.rst+1 added-1 removed
12 unmodified lines13 GitHub14 ------15 16 The 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>`_.18 19 Twitter20 -------21 10 unmodified linesmodified:docs/dev/contributing.rst+1 added-1 removed
195 unmodified lines196 through the `GitHub issues`_, **both open and closed**, to confirm that the bug197 hasn't been reported before. Duplicate bug reports are a huge drain on the time198 of other contributors, and should be avoided as much as possible.199 200-.. _GitHub issues: https://github.com/requests/requests/issues200+.. _GitHub issues: https://github.com/psf/requests/issues201 202 203 Feature Requests204 ----------------12 unmodified linesmodified:docs/dev/todo.rst+2 added-2 removed
6 unmodified lines7 8 #. 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>`_.16 17 Feature Freeze18 --------------19 45 unmodified linesmodified:docs/user/advanced.rst+6 added-6 removed
298 unmodified lines299 immediately. You can override this behaviour and defer downloading the response300 body until you access the :attr:`Response.content <requests.Response.content>`301 attribute with the ``stream`` parameter::302 303- 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)305 306 At this point only the response headers have been downloaded and the connection307 remains open, hence allowing us to make content retrieval conditional::371 unmodified lines679 from GitHub. Suppose we wanted commit ``a050faf`` on Requests. We would get it680 like so::681 682 >>> 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')684 685 We should confirm that GitHub responded correctly. If it has, we want to work686 out what type of content it is. Do this like so::687 46 unmodified lines734 we should probably avoid making ham-handed POSTS to it. Instead, let's play735 with the Issues feature of GitHub.736 737 This 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 that739 this issue already exists, we will use it as an example. Let's start by getting it.740 741 ::742 743- >>> 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 200746 747 >>> issue = json.loads(r.text)34 unmodified lines782 783 ::784 785 >>> 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"787 788 >>> r = requests.post(url=url, data=body)789 >>> r.status_code790 40425 unmodified lines816 >>> print(content[u"id"])817 5804413818 819 >>> 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"821 822 >>> r = requests.patch(url=url, data=body, auth=auth)823 >>> r.status_code824 200208 unmodified linesmodified:docs/user/install.rst+4 added-4 removed
23 unmodified lines24 Get the Source Code25 -------------------26 27 Requests is actively developed on GitHub, where the code is28-`always available <https://github.com/requests/requests>`_.28+`always available <https://github.com/psf/requests>`_.29 30 You can either clone the public repository::31 32- $ git clone git://github.com/requests/requests.git32+ $ git clone git://github.com/psf/requests.git33 34-Or, download the `tarball <https://github.com/requests/requests/tarball/master>`_::34+Or, download the `tarball <https://github.com/psf/requests/tarball/master>`_::35 36- $ 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).38 39 Once you have a copy of the source, you can embed it in your own Python40 package, or install it into your site-packages easily::3 unmodified linesmodified:docs/index.rst+2 added-2 removed
15 unmodified lines16 17 .. image:: https://img.shields.io/pypi/pyversions/requests.svg18 :target: https://pypi.org/project/requests/19 20-.. 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.io23 24 .. image:: https://img.shields.io/badge/Say%20Thanks!-🦉-1EAEDB.svg25 :target: https://saythanks.io/to/kennethreitz149 unmodified linesmodified:requests/adapters.py+13 added-58 removed
433 unmodified lines434 else:435 timeout = TimeoutSauce(connect=timeout, read=timeout)436 437 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+ )451 452- # Send the request.453- else:454- if hasattr(conn, 'proxy_pool'):455- conn = conn.proxy_pool456-457- low_conn = conn._get_conn(timeout=DEFAULT_POOL_TIMEOUT)458-459- try:460- low_conn.putrequest(request.method,461- url,462- skip_accept_encoding=True)463-464- for header, value in request.headers.items():465- low_conn.putheader(header, value)466-467- low_conn.endheaders()468-469- 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')475-476- # 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()483-484- 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- raise496-452 except (ProtocolError, socket.error) as err:453 raise ConnectionError(err, request=request)454 455 except MaxRetryError as e:33 unmodified linesmodified:requests/api.py+1 added-1 removed
14 unmodified lines15 16 def request(method, url, **kwargs):17 """Constructs and sends a :class:`Request <Request>`.18 19- :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-like138 unmodified linesmodified:requests/auth.py+1 added-1 removed
237 unmodified lines238 :rtype: requests.Response239 """240 241 # 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 linesmodified:requests/compat.py+2 added
41 unmodified lines42 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, OrderedDict48 49 50 builtin_str = str8 unmodified lines59 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, MutableMapping66 67 builtin_str = str5 unmodified linesmodified:requests/models.py+22 added-5 removed
10 unmodified lines11 import sys12 13 # 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.16 import encodings.idna17 18 from urllib3.fields import RequestField19 from urllib3.filepost import encode_multipart_formdata338 unmodified lines358 #: 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 lines640 #: The :class:`PreparedRequest <PreparedRequest>` object to which this641 #: is a response.642 self.request = None643 644+ #: 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 = None647+648 def __enter__(self):649 return self650 651 def __exit__(self, *args):101 unmodified lines753 if hasattr(self.raw, 'stream'):754 try:755 for chunk in self.raw.stream(chunk_size, decode_content=True):756 yield chunk757+758 except ProtocolError as e:754- raise ChunkedEncodingError(e)759+ self._error = ChunkedEncodingError(e)760+761 except DecodeError as e:756- raise ContentDecodingError(e)762+ self._error = ContentDecodingError(e)763+764 except ReadTimeoutError as e:758- raise ConnectionError(e)765+ self._error = ConnectionError(e)766+767+ finally:768+ # if we had an error - throw the saved error769+ if self._error:770+ raise self._error771+772 else:773 # Standard file-like object.774 while True:775 chunk = self.raw.read(chunk_size)64 unmodified lines840 self._content = None841 else:842 self._content = b''.join(self.iter_content(CONTENT_CHUNK_SIZE)) or b''843 844+ # if we had an error - throw the saved error845+ if self._error is not None:846+ raise self._error847+848 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._content120 unmodified linesmodified:requests/sessions.py+16 added-12 removed
9 unmodified lines10 import os11 import sys12 import time13 from datetime import timedelta14+from collections import OrderedDict15 16 from .auth import _basic_auth_str16-from .compat import cookielib, is_py3, OrderedDict, urljoin, urlparse, Mapping17+from .compat import cookielib, is_py3, urljoin, urlparse, Mapping18 from .cookies import (19 cookiejar_from_dict, extract_cookies_to_jar, RequestsCookieJar, merge_cookies)20 from .models import Request, PreparedRequest, DEFAULT_REDIRECT_LIMIT21 from .hooks import default_hooks, dispatch_hook72 unmodified lines94 95 96 class SessionRedirectMixin(object):97 98+ def __init__(self):99+ #: A list of domains that will be excluded from auth stripping100+ self.trusted_domains = []101+102 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 twice17 unmodified lines123 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 requests34 unmodified lines167 except (ChunkedEncodingError, ContentDecodingError, RuntimeError):168 resp.raw.read(decode_content=False)169 170 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)172 173 # Release the connection back into the pool.174 resp.close()175 176 # 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])180 181 # 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 lines197 prepared_request.url = to_native_string(url)198 199 self.rebuild_method(prepared_request, resp)200 195- # 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 = None208 209 headers = prepared_request.headers204- try:205- del headers['Cookie']206- except KeyError:207- pass210+ headers.pop('Cookie', None)211 212 # 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 lines273 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)276 274- return277 278 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 by137 unmodified lines418 self.adapters = OrderedDict()419 self.mount('https://', HTTPAdapter())420 self.mount('http://', HTTPAdapter())421 422+ super().__init__()423+424 def __enter__(self):425 return self426 427 def __exit__(self, *args):303 unmodified lines731 if url.lower().startswith(prefix.lower()):732 return adapter733 734 # 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))736 737 def close(self):738 """Closes all adapters and as such the session"""739 for v in self.adapters.values():35 unmodified linesmodified:requests/structures.py+3 added-1 removed
5 unmodified lines6 7 Data structures that power Requests.8 """9 10-from .compat import OrderedDict, Mapping, MutableMapping10+from collections import OrderedDict11 12+from .compat import Mapping, MutableMapping13 14+15 class CaseInsensitiveDict(MutableMapping):16 """A case-insensitive ``dict``-like object.17 18 Implements all methods and operations of87 unmodified linesmodified:requests/utils.py+3 added-2 removed
17 unmodified lines18 import sys19 import tempfile20 import warnings21 import zipfile22+from collections import OrderedDict23 24 from .__version__ import __version__25 from . import certs26 # to_native_string is unused here, but imported here for backwards compatibility27 from ._internal_utils import to_native_string28 from .compat import parse_http_list as _parse_list_header29 from .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)33 from .cookies import cookiejar_from_dict34 from .structures import CaseInsensitiveDict144 unmodified lines179 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 return185 186 if os.path.exists(loc):187 netrc_path = loc795 unmodified linesmodified:tests/test_lowlevel.py+43 added-2 removed
1 unmodified line2 3 import pytest4 import threading5 import requests6+from requests.exceptions import ChunkedEncodingError7 8 from tests.testserver.server import Server, consume_socket_content9 10 from .utils import override_environ17 unmodified lines28 def 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.31 31- 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 lines138 139 def test_digestauth_only_on_4xx():140 """Ensure we only send digestauth on 4xx challenges.141 141- 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 lines307 # Verify previous fragment is used and not the original.308 assert r.url == 'http://{}:{}/final-url/#relevant-section'.format(host, port)309 310 close_server.set()311+312+313+def test_response_content_retains_error():314+ """Verify that accessing response.content retains an error.315+316+ See https://github.com/kennethreitz/requests/issues/4965317+ """318+319+ data = "Some random stuff to read from remove server.\n"320+321+ def response_handler(sock):322+ req = consume_socket_content(sock, timeout=0.5)323+324+ # 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+ )330+331+ close_server = threading.Event()332+ server = Server(response_handler, wait_to_close_event=close_server)333+334+ 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.content339+340+ # Access the bad response data again, I would expect the same341+ # error again.342+343+ 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 lines17 from requests.adapters import HTTPAdapter18 from requests.auth import HTTPDigestAuth, _basic_auth_str19 from requests.compat import (20 Morsel, cookielib, getproxies, str, urlparse,21- builtin_str, OrderedDict)21+ builtin_str)22 from requests.cookies import (23 cookiejar_from_dict, morsel_to_cookie)24 from requests.exceptions import (25 ConnectionError, ConnectTimeout, InvalidSchema, InvalidURL,103 unmodified lines129 request = requests.Request('GET', url, params={"a": "b"}).prepare()130 assert request.url == expected131 132 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 lines445 446 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 lines465 466 @pytest.mark.parametrize('key', ('User-agent', 'user-agent'))467 def test_user_agent_transfers(self, httpbin, key):468 469- heads = {key: 'Mozilla/5.0 (github.com/requests/requests)'}469+ heads = {key: 'Mozilla/5.0 (github.com/psf/requests)'}470 471 r = requests.get(httpbin('user-agent'), headers=heads)472 assert heads[key] in r.text473 1737 unmodified lines2211 except ConnectTimeout:2212 pass2213 2214 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.ok2218 2219 308 unmodified linesmodified:tests/test_utils.py+3 added-2 removed
31 unmodified lines32 @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()) == 0355 unmodified lines397 'http://example.com/fiz?buz=%25ppicture',398 ),399 ))400 def 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) == expected403 404 405 @pytest.mark.parametrize(378 unmodified linesmodified:.travis.yml+1 added-14 removed
1 unmodified line2 # command to install dependencies3 install: "make"4 # command to run tests5 script:6- - |7- make test-readme6+ - make test-readme7 - make ci8 cache: pip9 jobs: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 linemodified:AUTHORS.rst+2 added
189 unmodified lines190 - 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 lines792 793 - 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))797 798 2.4.2 (2014-10-05)799 ------------------800 801 **Improvements**802 803 - 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))807 808 **Bugfixes**809 810 - 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))815 816 **Documentation**817 818 - 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/))824 825 2.4.1 (2014-09-09)826 ------------------827 823 unmodified linesmodified:README.md+7 added-7 removed
2 unmodified lines3 4 [](https://pypi.org/project/requests/)5 [](https://pypi.org/project/requests/)6 [](https://pypi.org/project/requests/)7-[](https://codecov.io/github/requests/requests)8-[](https://github.com/requests/requests/graphs/contributors)7+[](https://codecov.io/github/psf/requests)8+[](https://github.com/psf/requests/graphs/contributors)9 [](https://saythanks.io/to/kennethreitz)10 11 Requests is the only *Non-GMO* HTTP library for Python, safe for human12 consumption.18 unmodified lines31 ```32 33 See [the similar code, sans Requests](https://gist.github.com/973705).34 35-[](http://docs.python-requests.org/)35+[](http://docs.python-requests.org/)36 37 Requests allows you to send *organic, grass-fed* HTTP/1.1 requests,38 without the need for manual labor. There's no need to manually add query39 strings to your URLs, or to form-encode your POST data. Keep-alive and40 HTTP connection pooling are 100% automatic, thanks to41 [urllib3](https://github.com/shazow/urllib3).42 43 Besides, all the cool kids are doing it. Requests is one of the most44-downloaded Python packages of all time, pulling in over 11,000,00044+downloaded Python packages of all time, pulling in over 50,000,00045 downloads every month. You don't want to be left out!46 47 Feature Support48 ---------------43 unmodified lines92 93 1. 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/).94 2. 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.99-3. Fork [the repository](https://github.com/requests/requests) on99+3. Fork [the repository](https://github.com/psf/requests) on100 GitHub to start making your changes to the **master** branch (or101 branch off of it).102 4. Write a test which shows that the bug was fixed or that the feature103 works as expected.104 5. 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 lines53 '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 ]59 60 about = {}61 with open(os.path.join(here, 'requests', '__version__.py'), 'r', 'utf-8') as f:42 unmodified lines104 '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 )