Skip to content
Myr

Merged master

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

authored by Braulio Valdivielso Martínez · committed by Braulio Valdivielso Martínez · parents 9ac5a6e, 4618423 · Browse files · 70 files+3330 added−3483 removed
This commit

State

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

Diff stats

70 files+3330 added−3483 removed

  • tests:+1876 added−0 removed
  • other:+1454 added−3483 removed

70 files+3330 added−3483 removed

added:docs/_static/konami.js+116 added
1/*2 * Konami-JS ~3 * :: Now with support for touch events and multiple instances for4 * :: those situations that call for multiple easter eggs!5 * Code: http://konami-js.googlecode.com/6 * Examples: http://www.snaptortoise.com/konami-js7 * Copyright (c) 2009 George Mandis (georgemandis.com, snaptortoise.com)8 * Version: 1.4.2 (9/2/2013)9 * Licensed under the MIT License (http://opensource.org/licenses/MIT)10 * Tested in: Safari 4+, Google Chrome 4+, Firefox 3+, IE7+, Mobile Safari 2.2.1 and Dolphin Browser11 */1213var Konami = function (callback) {14 var konami = {15 addEvent: function (obj, type, fn, ref_obj) {16 if (obj.addEventListener)17 obj.addEventListener(type, fn, false);18 else if (obj.attachEvent) {19 // IE20 obj["e" + type + fn] = fn;21 obj[type + fn] = function () {22 obj["e" + type + fn](window.event, ref_obj);23 };24 obj.attachEvent("on" + type, obj[type + fn]);25 }26 },27 input: "",28 pattern: "38384040373937396665",29 load: function (link) {30 this.addEvent(document, "keydown", function (e, ref_obj) {31 if (ref_obj) konami = ref_obj; // IE32 konami.input += e ? e.keyCode : event.keyCode;33 if (konami.input.length > konami.pattern.length)34 konami.input = konami.input.substr((konami.input.length - konami.pattern.length));35 if (konami.input == konami.pattern) {36 konami.code(link);37 konami.input = "";38 e.preventDefault();39 return false;40 }41 }, this);42 this.iphone.load(link);43 },44 code: function (link) {45 window.location = link46 },47 iphone: {48 start_x: 0,49 start_y: 0,50 stop_x: 0,51 stop_y: 0,52 tapTolerance: 8,53 capture: false,54 orig_keys: "",55 keys: ["UP", "UP", "DOWN", "DOWN", "LEFT", "RIGHT", "LEFT", "RIGHT", "TAP", "TAP"],56 code: function (link) {57 konami.code(link);58 },59 touchCapture: function(evt) {60 konami.iphone.start_x = evt.changedTouches[0].pageX;61 konami.iphone.start_y = evt.changedTouches[0].pageY;62 konami.iphone.capture = true; 63 },64 load: function (link) {65 this.orig_keys = this.keys;66 konami.addEvent(document, "touchmove", function (e) {67 if (e.touches.length == 1 && konami.iphone.capture == true) {68 var touch = e.touches[0];69 konami.iphone.stop_x = touch.pageX;70 konami.iphone.stop_y = touch.pageY;71 konami.iphone.check_direction();72 }73 });74 konami.addEvent(document, "touchend", function (evt) {75 konami.touchCapture(evt);76 konami.iphone.check_direction(link);77 }, false);78 konami.addEvent(document, "touchstart", function (evt) {79 konami.touchCapture(evt);80 });81 },82 check_direction: function (link) {83 var x_magnitude = Math.abs(this.start_x - this.stop_x);84 var y_magnitude = Math.abs(this.start_y - this.stop_y);85 var hasMoved = (x_magnitude > this.tapTolerance || y_magnitude > this.tapTolerance);86 var result;87 if (this.capture === true && hasMoved) {88 this.capture = false;89 var x = ((this.start_x - this.stop_x) < 0) ? "RIGHT" : "LEFT";90 var y = ((this.start_y - this.stop_y) < 0) ? "DOWN" : "UP";91 var result = (x_magnitude > y_magnitude) ? x : y;92 }93 else if (this.capture === false && !hasMoved) {94 result = (this.tap == true) ? "TAP" : result;95 result = "TAP";96 }97 if (result) {98 if (result == this.keys[0]) this.keys = this.keys.slice(1, this.keys.length);99 else this.keys = this.orig_keys;100 }101 if (this.keys.length == 0) {102 this.keys = this.orig_keys;103 this.code(link);104 }105 }106 }107 }108109 typeof callback === "string" && konami.load(callback);110 if (typeof callback === "function") {111 konami.code = callback;112 konami.load();113 }114115 return konami;116};
added:docs/_templates/hacks.html+54 added
modified:docs/_templates/sidebarintro.html+31 added-16 removed
modified:docs/_templates/sidebarlogo.html+33 added-6 removed
deleted:docs/_themes/kr/static/flasky.css_t-536 removed
1/*2 * flasky.css_t3 * ~~~~~~~~~~~~4 *5 * :copyright: Copyright 2010 by Armin Ronacher. Modifications by Kenneth Reitz.6 * :license: Flask Design License, see LICENSE for details.7 */89{% set page_width = '940px' %}10{% set sidebar_width = '220px' %}1112@import url("basic.css");1314/* -- page layout ----------------------------------------------------------- */1516body {17 font-family: 'goudy old style', 'minion pro', 'bell mt', Georgia, 'Hiragino Mincho Pro';18 font-size: 17px;19 background-color: white;20 color: #000;21 margin: 0;22 padding: 0;23}2425div.document {26 width: {{ page_width }};27 margin: 30px auto 0 auto;28}2930div.documentwrapper {31 float: left;32 width: 100%;33}3435div.bodywrapper {36 margin: 0 0 0 {{ sidebar_width }};37}3839div.sphinxsidebar {40 width: {{ sidebar_width }};41}4243hr {44 border: 1px solid #B1B4B6;45}4647div.body {48 background-color: #ffffff;49 color: #3E4349;50 padding: 0 30px 0 30px;51}5253img.floatingflask {54 padding: 0 0 10px 10px;55 float: right;56}5758div.footer {59 width: {{ page_width }};60 margin: 20px auto 30px auto;61 font-size: 14px;62 color: #888;63 text-align: right;64}6566div.footer a {67 color: #888;68}6970div.related {71 display: none;72}7374div.sphinxsidebar a {75 color: #444;76 text-decoration: none;77 border-bottom: 1px dotted #999;78}7980div.sphinxsidebar a:hover {81 border-bottom: 1px solid #999;82}8384div.sphinxsidebar {85 font-size: 14px;86 line-height: 1.5;87}8889div.sphinxsidebarwrapper {90 padding: 18px 10px;91}9293div.sphinxsidebarwrapper p.logo {94 padding: 0;95 margin: -10px 0 0 -20px;96 text-align: center;97}9899div.sphinxsidebar h3,100div.sphinxsidebar h4 {101 font-family: 'Garamond', 'Georgia', serif;102 color: #444;103 font-size: 24px;104 font-weight: normal;105 margin: 0 0 5px 0;106 padding: 0;107}108109div.sphinxsidebar h4 {110 font-size: 20px;111}112113div.sphinxsidebar h3 a {114 color: #444;115}116117div.sphinxsidebar p.logo a,118div.sphinxsidebar h3 a,119div.sphinxsidebar p.logo a:hover,120div.sphinxsidebar h3 a:hover {121 border: none;122}123124div.sphinxsidebar p {125 color: #555;126 margin: 10px 0;127}128129div.sphinxsidebar ul {130 margin: 10px 0;131 padding: 0;132 color: #000;133}134135div.sphinxsidebar input {136 border: 1px solid #ccc;137 font-family: 'Georgia', serif;138 font-size: 1em;139}140141/* -- body styles ----------------------------------------------------------- */142143a {144 color: #004B6B;145 text-decoration: underline;146}147148a:hover {149 color: #6D4100;150 text-decoration: underline;151}152153div.body h1,154div.body h2,155div.body h3,156div.body h4,157div.body h5,158div.body h6 {159 font-family: 'Garamond', 'Georgia', serif;160 font-weight: normal;161 margin: 30px 0px 10px 0px;162 padding: 0;163}164165div.body h1 { margin-top: 0; padding-top: 0; font-size: 240%; }166div.body h2 { font-size: 180%; }167div.body h3 { font-size: 150%; }168div.body h4 { font-size: 130%; }169div.body h5 { font-size: 100%; }170div.body h6 { font-size: 100%; }171172a.headerlink {173 color: #ddd;174 padding: 0 4px;175 text-decoration: none;176}177178a.headerlink:hover {179 color: #444;180 background: #eaeaea;181}182183div.body p, div.body dd, div.body li {184 line-height: 1.4em;185}186187div.admonition {188 background: #fafafa;189 margin: 20px -30px;190 padding: 10px 30px;191 border-top: 1px solid #ccc;192 border-bottom: 1px solid #ccc;193}194195div.admonition tt.xref, div.admonition a tt {196 border-bottom: 1px solid #fafafa;197}198199dd div.admonition {200 margin-left: -60px;201 padding-left: 60px;202}203204div.admonition p.admonition-title {205 font-family: 'Garamond', 'Georgia', serif;206 font-weight: normal;207 font-size: 24px;208 margin: 0 0 10px 0;209 padding: 0;210 line-height: 1;211}212213div.admonition p.last {214 margin-bottom: 0;215}216217div.highlight {218 background-color: white;219}220221dt:target, .highlight {222 background: #FAF3E8;223}224225div.note {226 background-color: #eee;227 border: 1px solid #ccc;228}229230div.seealso {231 background-color: #ffc;232 border: 1px solid #ff6;233}234235div.topic {236 background-color: #eee;237}238239p.admonition-title {240 display: inline;241}242243p.admonition-title:after {244 content: ":";245}246247pre, tt {248 font-family: 'Consolas', 'Menlo', 'Deja Vu Sans Mono', 'Bitstream Vera Sans Mono', monospace;249 font-size: 0.9em;250}251252img.screenshot {253}254255tt.descname, tt.descclassname {256 font-size: 0.95em;257}258259tt.descname {260 padding-right: 0.08em;261}262263img.screenshot {264 -moz-box-shadow: 2px 2px 4px #eee;265 -webkit-box-shadow: 2px 2px 4px #eee;266 box-shadow: 2px 2px 4px #eee;267}268269table.docutils {270 border: 1px solid #888;271 -moz-box-shadow: 2px 2px 4px #eee;272 -webkit-box-shadow: 2px 2px 4px #eee;273 box-shadow: 2px 2px 4px #eee;274}275276table.docutils td, table.docutils th {277 border: 1px solid #888;278 padding: 0.25em 0.7em;279}280281table.field-list, table.footnote {282 border: none;283 -moz-box-shadow: none;284 -webkit-box-shadow: none;285 box-shadow: none;286}287288table.footnote {289 margin: 15px 0;290 width: 100%;291 border: 1px solid #eee;292 background: #fdfdfd;293 font-size: 0.9em;294}295296table.footnote + table.footnote {297 margin-top: -15px;298 border-top: none;299}300301table.field-list th {302 padding: 0 0.8em 0 0;303}304305table.field-list td {306 padding: 0;307}308309table.footnote td.label {310 width: 0px;311 padding: 0.3em 0 0.3em 0.5em;312}313314table.footnote td {315 padding: 0.3em 0.5em;316}317318dl {319 margin: 0;320 padding: 0;321}322323dl dd {324 margin-left: 30px;325}326327blockquote {328 margin: 0 0 0 30px;329 padding: 0;330}331332ul, ol {333 margin: 10px 0 10px 30px;334 padding: 0;335}336337pre {338 background: #eee;339 padding: 7px 30px;340 margin: 15px -30px;341 line-height: 1.3em;342}343344dl pre, blockquote pre, li pre {345 margin-left: -60px;346 padding-left: 60px;347}348349dl dl pre {350 margin-left: -90px;351 padding-left: 90px;352}353354tt {355 background-color: #ecf0f3;356 color: #222;357 /* padding: 1px 2px; */358}359360tt.xref, a tt {361 background-color: #FBFBFB;362 border-bottom: 1px solid white;363}364365a.reference {366 text-decoration: none;367 border-bottom: 1px dotted #004B6B;368}369370a.reference:hover {371 border-bottom: 1px solid #6D4100;372}373374a.footnote-reference {375 text-decoration: none;376 font-size: 0.7em;377 vertical-align: top;378 border-bottom: 1px dotted #004B6B;379}380381a.footnote-reference:hover {382 border-bottom: 1px solid #6D4100;383}384385a:hover tt {386 background: #EEE;387}388389390@media screen and (max-width: 870px) {391392 div.sphinxsidebar {393 display: none;394 }395396 div.document {397 width: 100%;398399 }400401 div.documentwrapper {402 margin-left: 0;403 margin-top: 0;404 margin-right: 0;405 margin-bottom: 0;406 }407408 div.bodywrapper {409 margin-top: 0;410 margin-right: 0;411 margin-bottom: 0;412 margin-left: 0;413 }414415 ul {416 margin-left: 0;417 }418419 .document {420 width: auto;421 }422423 .footer {424 width: auto;425 }426427 .bodywrapper {428 margin: 0;429 }430431 .footer {432 width: auto;433 }434435 .github {436 display: none;437 }438439440441}442443444445@media screen and (max-width: 875px) {446447 body {448 margin: 0;449 padding: 20px 30px;450 }451452 div.documentwrapper {453 float: none;454 background: white;455 }456457 div.sphinxsidebar {458 display: block;459 float: none;460 width: 102.5%;461 margin: 50px -30px -20px -30px;462 padding: 10px 20px;463 background: #333;464 color: white;465 }466467 div.sphinxsidebar h3, div.sphinxsidebar h4, div.sphinxsidebar p,468 div.sphinxsidebar h3 a {469 color: white;470 }471472 div.sphinxsidebar a {473 color: #aaa;474 }475476 div.sphinxsidebar p.logo {477 display: none;478 }479480 div.document {481 width: 100%;482 margin: 0;483 }484485 div.related {486 display: block;487 margin: 0;488 padding: 10px 0 20px 0;489 }490491 div.related ul,492 div.related ul li {493 margin: 0;494 padding: 0;495 }496497 div.footer {498 display: none;499 }500501 div.bodywrapper {502 margin: 0;503 }504505 div.body {506 min-height: 0;507 padding: 0;508 }509510 .rtd_doc_footer {511 display: none;512 }513514 .document {515 width: auto;516 }517518 .footer {519 width: auto;520 }521522 .footer {523 width: auto;524 }525526 .github {527 display: none;528 }529}530531532/* misc. */533534.revsys-inline {535 display: none!important;536}
deleted:docs/_themes/kr/layout.html-85 removed
1{%- extends "basic/layout.html" %}2{%- block extrahead %}3 {{ super() }}4 {% if theme_touch_icon %}5 <link rel="apple-touch-icon" href="{{ pathto('_static/' ~ theme_touch_icon, 1) }}" />6 {% endif %}7 <meta name="viewport" content="width=device-width, initial-scale=0.9, maximum-scale=0.9">8 <script type="text/javascript" src="https://gumroad.com/js/gumroad.js"></script>9{% endblock %}10{%- block relbar2 %}{% endblock %}11{%- block footer %}12 <div class="footer">13 &copy; Copyright {{ copyright }}.14 </div>15 <a href="https://github.com/kennethreitz/requests" class="github">16 <img style="position: absolute; top: 0; right: 0; border: 0;" src="http://s3.amazonaws.com/github/ribbons/forkme_right_darkblue_121621.png" alt="Fork me on GitHub" class="github"/>17 </a>1819 <script type="text/javascript" src="https://gumroad.com/js/gumroad.js"></script>2021 <script type="text/javascript">22 /* <![CDATA[ */23 (function() {24 var s = document.createElement('script'), t = document.getElementsByTagName('script')[0];25 s.type = 'text/javascript';26 s.async = true;27 s.src = 'http://api.flattr.com/js/0.6/load.js?mode=auto';28 t.parentNode.insertBefore(s, t);29 })();30 /* ]]> */31 </script>32 <script type="text/javascript">33 setTimeout(function(){var a=document.createElement("script");34 var b=document.getElementsByTagName("script")[0];35 a.src=document.location.protocol+"//dnn506yrbagrg.cloudfront.net/pages/scripts/0013/7219.js?"+Math.floor(new Date().getTime()/3600000);36 a.async=true;a.type="text/javascript";b.parentNode.insertBefore(a,b)}, 1);37 </script>3839 <script type="text/javascript">40 new HelloBar(36402,48802);41 </script>424344 <script type="text/javascript">4546 var _gaq = _gaq || [];47 _gaq.push(['_setAccount', 'UA-8742933-11']);48 _gaq.push(['_setDomainName', 'none']);49 _gaq.push(['_setAllowLinker', true]);50 _gaq.push(['_trackPageview']);5152 (function() {53 var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;54 ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';55 var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);56 })();5758 </script>5960 <script type="text/javascript">61 (function() {62 var t = document.createElement('script');63 t.type = 'text/javascript';64 t.async = true;65 t.id = 'gauges-tracker';66 t.setAttribute('data-site-id',67 '4ddc27f6613f5d186d000007');68 t.src = '//secure.gaug.es/track.js';69 var s = document.getElementsByTagName('script')[0];70 s.parentNode.insertBefore(t, s);71 })();72 </script>7374 <script type="text/javascript">75 (function() {76 window._pa = window._pa || {};77 _pa.productId = "requests-docs";78 var pa = document.createElement('script'); pa.type = 'text/javascript'; pa.async = true;79 pa.src = ('https:' == document.location.protocol ? 'https:' : 'http:') + "//tag.perfectaudience.com/serve/5226171f87bc6890da0000a0.js";80 var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(pa, s);81 })();82</script>838485{%- endblock %}
deleted:docs/_themes/kr/relations.html-19 removed
deleted:docs/_themes/kr/theme.conf-7 removed
1[theme]2inherit = basic3stylesheet = flasky.css4pygments_style = flask_theme_support.FlaskyStyle56[options]7touch_icon =
deleted:docs/_themes/kr_small/static/flasky.css_t-287 removed
1/*2 * flasky.css_t3 * ~~~~~~~~~~~~4 *5 * Sphinx stylesheet -- flasky theme based on nature theme.6 *7 * :copyright: Copyright 2007-2010 by the Sphinx team, see AUTHORS.8 * :license: BSD, see LICENSE for details.9 *10 */1112@import url("basic.css");1314/* -- page layout ----------------------------------------------------------- */1516body {17 font-family: 'Georgia', serif;18 font-size: 17px;19 color: #000;20 background: white;21 margin: 0;22 padding: 0;23}2425div.documentwrapper {26 float: left;27 width: 100%;28}2930div.bodywrapper {31 margin: 40px auto 0 auto;32 width: 700px;33}3435hr {36 border: 1px solid #B1B4B6;37}3839div.body {40 background-color: #ffffff;41 color: #3E4349;42 padding: 0 30px 30px 30px;43}4445img.floatingflask {46 padding: 0 0 10px 10px;47 float: right;48}4950div.footer {51 text-align: right;52 color: #888;53 padding: 10px;54 font-size: 14px;55 width: 650px;56 margin: 0 auto 40px auto;57}5859div.footer a {60 color: #888;61 text-decoration: underline;62}6364div.related {65 line-height: 32px;66 color: #888;67}6869div.related ul {70 padding: 0 0 0 10px;71}7273div.related a {74 color: #444;75}7677/* -- body styles ----------------------------------------------------------- */7879a {80 color: #004B6B;81 text-decoration: underline;82}8384a:hover {85 color: #6D4100;86 text-decoration: underline;87}8889div.body {90 padding-bottom: 40px; /* saved for footer */91}9293div.body h1,94div.body h2,95div.body h3,96div.body h4,97div.body h5,98div.body h6 {99 font-family: 'Garamond', 'Georgia', serif;100 font-weight: normal;101 margin: 30px 0px 10px 0px;102 padding: 0;103}104105{% if theme_index_logo %}106div.indexwrapper h1 {107 text-indent: -999999px;108 background: url({{ theme_index_logo }}) no-repeat center center;109 height: {{ theme_index_logo_height }};110}111{% endif %}112113div.body h2 { font-size: 180%; }114div.body h3 { font-size: 150%; }115div.body h4 { font-size: 130%; }116div.body h5 { font-size: 100%; }117div.body h6 { font-size: 100%; }118119a.headerlink {120 color: white;121 padding: 0 4px;122 text-decoration: none;123}124125a.headerlink:hover {126 color: #444;127 background: #eaeaea;128}129130div.body p, div.body dd, div.body li {131 line-height: 1.4em;132}133134div.admonition {135 background: #fafafa;136 margin: 20px -30px;137 padding: 10px 30px;138 border-top: 1px solid #ccc;139 border-bottom: 1px solid #ccc;140}141142div.admonition p.admonition-title {143 font-family: 'Garamond', 'Georgia', serif;144 font-weight: normal;145 font-size: 24px;146 margin: 0 0 10px 0;147 padding: 0;148 line-height: 1;149}150151div.admonition p.last {152 margin-bottom: 0;153}154155div.highlight{156 background-color: white;157}158159dt:target, .highlight {160 background: #FAF3E8;161}162163div.note {164 background-color: #eee;165 border: 1px solid #ccc;166}167168div.seealso {169 background-color: #ffc;170 border: 1px solid #ff6;171}172173div.topic {174 background-color: #eee;175}176177div.warning {178 background-color: #ffe4e4;179 border: 1px solid #f66;180}181182p.admonition-title {183 display: inline;184}185186p.admonition-title:after {187 content: ":";188}189190pre, tt {191 font-family: 'Consolas', 'Menlo', 'Deja Vu Sans Mono', 'Bitstream Vera Sans Mono', monospace;192 font-size: 0.85em;193}194195img.screenshot {196}197198tt.descname, tt.descclassname {199 font-size: 0.95em;200}201202tt.descname {203 padding-right: 0.08em;204}205206img.screenshot {207 -moz-box-shadow: 2px 2px 4px #eee;208 -webkit-box-shadow: 2px 2px 4px #eee;209 box-shadow: 2px 2px 4px #eee;210}211212table.docutils {213 border: 1px solid #888;214 -moz-box-shadow: 2px 2px 4px #eee;215 -webkit-box-shadow: 2px 2px 4px #eee;216 box-shadow: 2px 2px 4px #eee;217}218219table.docutils td, table.docutils th {220 border: 1px solid #888;221 padding: 0.25em 0.7em;222}223224table.field-list, table.footnote {225 border: none;226 -moz-box-shadow: none;227 -webkit-box-shadow: none;228 box-shadow: none;229}230231table.footnote {232 margin: 15px 0;233 width: 100%;234 border: 1px solid #eee;235}236237table.field-list th {238 padding: 0 0.8em 0 0;239}240241table.field-list td {242 padding: 0;243}244245table.footnote td {246 padding: 0.5em;247}248249dl {250 margin: 0;251 padding: 0;252}253254dl dd {255 margin-left: 30px;256}257258pre {259 padding: 0;260 margin: 15px -30px;261 padding: 8px;262 line-height: 1.3em;263 padding: 7px 30px;264 background: #eee;265 border-radius: 2px;266 -moz-border-radius: 2px;267 -webkit-border-radius: 2px;268}269270dl pre {271 margin-left: -60px;272 padding-left: 60px;273}274275tt {276 background-color: #ecf0f3;277 color: #222;278 /* padding: 1px 2px; */279}280281tt.xref, a tt {282 background-color: #FBFBFB;283}284285a:hover tt {286 background: #EEE;287}
deleted:docs/_themes/kr_small/layout.html-22 removed
deleted:docs/_themes/kr_small/theme.conf-10 removed
1[theme]2inherit = basic3stylesheet = flasky.css4nosidebar = true5pygments_style = flask_theme_support.FlaskyStyle67[options]8index_logo = ''9index_logo_height = 120px10github_fork = ''
deleted:docs/_themes/README.rst-25 removed
1krTheme Sphinx Style2====================34This repository contains sphinx styles Kenneth Reitz uses in most of5his projects. It is a derivative of Mitsuhiko's themes for Flask and Flask related6projects. To use this style in your Sphinx documentation, follow7this guide:891. put this folder as _themes into your docs folder. Alternatively10 you can also use git submodules to check out the contents there.11122. add this to your conf.py: ::1314 sys.path.append(os.path.abspath('_themes'))15 html_theme_path = ['_themes']16 html_theme = 'flask'1718The following themes exist:1920**kr**21 the standard flask documentation theme for large projects2223**kr_small**24 small one-page theme. Intended to be used by very small addon libraries.25
modified:docs/dev/contributing.rst+94 added-33 removed
1 unmodified line
23Contributor's Guide4===================56If you're reading this you're probably interested in contributing to7Requests. First, We'd like to say: thank you! Open source projects8live-and-die based on the support they receive from others, and the fact that9you're even considering supporting Requests is very generous of10you.6If you're reading this, you're probably interested in contributing to Requests.7Thank you very much! Open source projects live-and-die based on the support8they receive from others, and the fact that you're even considering9contributing to the Requests project is *very* generous of you.1012This document lays out guidelines and advice for contributing to Requests.13If you're thinking of contributing, start by reading this thoroughly and14getting a feel for how contributing to the project works. If you have any11This document lays out guidelines and advice for contributing to this project.12If you're thinking of contributing, please start by reading this document and13getting a feel for how contributing to this project works. If you have any14questions, feel free to reach out to either `Ian Cordasco`_ or `Cory Benfield`_,15the primary maintainers.1618The guide is split into sections based on the type of contribution you're19thinking of making, with a section that covers general guidelines for all20contributors.2117.. _Ian Cordasco: http://www.coglib.com/~icordasc/18.. _Cory Benfield: https://lukasa.co.uk/about1920If you have non-technical feedback, philosophical ponderings, crazy ideas, or21other general thoughts about Requests or its position within the Python22ecosystem, the BDFL, `Kenneth Reitz`_, would love to hear from you.2326All Contributions27-----------------24The guide is split into sections based on the type of contribution you're25thinking of making, with a section that covers general guidelines for all26contributors.2728.. _Kenneth Reitz: mailto:me@kennethreitz.org2930Be Cordial30~~~~~~~~~~31----------3232**Be cordial or be on your way.**33 **Be cordial or be on your way**. *—Kenneth Reitz*3435Requests has one very important rule governing all forms of contribution,36including reporting bugs or requesting features. This golden rule is37"`be cordial or be on your way`_".3836`be cordial or be on your way`_. **All contributions are welcome**, as long as39**All contributions are welcome**, as long as40everyone involved is treated with respect.4142.. _be cordial or be on your way: http://kennethreitz.org/be-cordial-or-be-on-your-way/4344.. _early-feedback:4546Get Early Feedback44~~~~~~~~~~~~~~~~~~47------------------4849If you are contributing, do not feel the need to sit on your contribution until50it is perfectly polished and complete. It helps everyone involved for you to51seek feedback as early as you possibly can. Submitting an early, unfinished
1 unmodified line
53getting that contribution accepted, and can save you from putting a lot of work54into a contribution that is not suitable for the project.5556Contribution Suitability54~~~~~~~~~~~~~~~~~~~~~~~~57------------------------5856The project maintainer has the last word on whether or not a contribution is57suitable for Requests. All contributions will be considered, but from time58to time contributions will be rejected because they do not suit the project.59Our project maintainers have the last word on whether or not a contribution is60suitable for Requests. All contributions will be considered carefully, but from61time to time, contributions will be rejected because they do not suit the62current goals or needs of the project.6360If your contribution is rejected, don't despair! So long as you followed these61guidelines, you'll have a much better chance of getting your next contribution62accepted.64If your contribution is rejected, don't despair! As long as you followed these65guidelines, you will have a much better chance of getting your next66contribution accepted.676869Code Contributions70------------------7168Steps69~~~~~72Steps for Submitting Code73~~~~~~~~~~~~~~~~~~~~~~~~~7475When contributing code, you'll want to follow this checklist:76771. Fork the repository on GitHub.
29 unmodified lines
107asking for help.108109Please also check the :ref:`early-feedback` section.110111Kenneth Reitz's Code Style™112~~~~~~~~~~~~~~~~~~~~~~~~~~~113114The Requests codebase uses the `PEP 8`_ code style.115116In addition to the standards outlined in PEP 8, we have a few guidelines:117118- Line-length can exceed 79 characters, to 100, when convenient.119- Line-length can exceed 100 characters, when doing otherwise would be *terribly* inconvenient.120- Always use single-quoted strings (e.g. ``'#flatearth'``), unless a single-quote occurs within the string.121122Additionally, one of the styles that PEP8 recommends for `line continuations`_123completely lacks all sense of taste, and is not to be permitted within124the Requests codebase::125126 # Aligned with opening delimiter.127 foo = long_function_name(var_one, var_two,128 var_three, var_four)129130No. Just don't. Please.131132Docstrings are to follow the following syntaxes::133134 def the_earth_is_flat():135 """NASA divided up the seas into thirty-three degrees."""136 pass137138::139140 def fibonacci_spiral_tool():141 """With my feet upon the ground I lose myself / between the sounds142 and open wide to suck it in. / I feel it move across my skin. / I'm143 reaching up and reaching out. / I'm reaching for the random or144 whatever will bewilder me. / Whatever will bewilder me. / And145 following our will and wind we may just go where no one's been. /146 We'll ride the spiral to the end and may just go where no one's147 been.148149 Spiral out. Keep going...150 """151 pass152153All functions, methods, and classes are to contain docstrings. Object data154model methods (e.g. ``__repr__``) are typically the exception to this rule.155156Thanks for helping to make the world a better place!157158.. _PEP 8: http://pep8.org159.. _line continuations: https://www.python.org/dev/peps/pep-0008/#indentation160161Documentation Contributions162---------------------------163164Documentation improvements are always welcome! The documentation files live in165the ``docs/`` directory of the codebase. They're written in166`reStructuredText`_, and use `Sphinx`_ to generate the full suite of167documentation.168115When contributing documentation, please attempt to follow the style of the169When contributing documentation, please do your best to follow the style of the170documentation files. This means a soft-limit of 79 characters wide in your text117files and a semi-formal prose style.171files and a semi-formal, yet friendly and approachable, prose style.172173When presenting Python code, use single-quoted strings (``'hello'`` instead of174``"hello"``).175176.. _reStructuredText: http://docutils.sourceforge.net/rst.html177.. _Sphinx: http://sphinx-doc.org/index.html178179
12 unmodified lines
192193Feature Requests194----------------195139Requests is in a perpetual feature freeze. The maintainers believe that140requests contains every major feature currently required by the vast majority141of users.196Requests is in a perpetual feature freeze, only the BDFL can add or approve of197new features. The maintainers believe that Requests is a feature-complete198piece of software at this time.199200One of the most important skills to have while maintaining a largely-used201open source project is learning the ability to say "no" to suggested changes,202while keeping an open ear and mind.203204If you believe there is a feature missing, feel free to raise a feature205request, but please do be aware that the overwhelming likelihood is that your145feature request will not be accepted.206feature request will not be accepted.
modified:docs/user/advanced.rst+47 added-29 removed
22 unmodified lines
2324 s = requests.Session()2526 s.get('http://httpbin.org/cookies/set/sessioncookie/123456789')27 r = s.get("http://httpbin.org/cookies")27 r = s.get('http://httpbin.org/cookies')2829 print(r.text)30 # '{"cookies": {"sessioncookie": "123456789"}}'31
17 unmodified lines
49requests, even if using a session. This example will only send the cookies50with the first request, but not the second::5152 s = requests.Session()5354 r = s.get('http://httpbin.org/cookies', cookies={'from-my': 'browser'})55 print(r.text)56 # '{"cookies": {"from-my": "browser"}}'57
71 unmodified lines
129130 from requests import Request, Session131132 s = Session()132 req = Request('GET', url,133 data=data,134 headers=header135 )133134 req = Request('POST', url, data=data, headers=headers)135 prepped = req.prepare()136137 # do something with prepped.body138 prepped.body = 'No, I want exactly this as the body.'139140 # do something with prepped.headers141 del prepped.headers['Content-Type']142143 resp = s.send(prepped,144 stream=stream,145 verify=verify,
20 unmodified lines
166167 from requests import Request, Session168169 s = Session()168 req = Request('GET', url,169 data=data170 headers=headers171 )170 req = Request('GET', url, data=data, headers=headers)171172 prepped = s.prepare_request(req)173174 # do something with prepped.body175 prepped.body = 'Seriously, send exactly these bytes.'176177 # do something with prepped.headers178 prepped.headers['Keep-Dead'] = 'parrot'179180 resp = s.send(prepped,181 stream=stream,182 verify=verify,
38 unmodified lines
221You can also specify a local cert to use as client side certificate, as a single222file (containing the private key and the certificate) or as a tuple of both223file's path::224223 >>> requests.get('https://kennethreitz.com', cert=('/path/server.crt', '/path/key'))225 >>> requests.get('https://kennethreitz.com', cert=('/path/client.cert', '/path/client.key'))226 <Response [200]>227228If you specify a wrong path or an invalid cert::229228 >>> requests.get('https://kennethreitz.com', cert='/wrong_path/server.pem')230 >>> requests.get('https://kennethreitz.com', cert='/wrong_path/client.pem')231 SSLError: [Errno 336265225] _ssl.c:347: error:140B0009:SSL routines:SSL_CTX_use_PrivateKey_file:PEM lib232233.. warning:: The private key to your local certificate *must* be unencrypted.234 Currently, requests does not support using encrypted keys.235236.. _ca-certificates:237238CA Certificates239---------------
117 unmodified lines
357POST Multiple Multipart-Encoded Files358-------------------------------------359360You can send multiple files in one request. For example, suppose you want to356upload image files to an HTML form with a multiple file field 'images':361upload image files to an HTML form with a multiple file field 'images'::362363 <input type="file" name="images" multiple="true" required="true"/>364360To do that, just set files to a list of tuples of (form_field_name, file_info):365To do that, just set files to a list of tuples of ``(form_field_name, file_info)``::366367 >>> url = 'http://httpbin.org/post'368 >>> multiple_files = [363 >>> multiple_files = [('images', ('foo.png', open('foo.png', 'rb'), 'image/png')),364 ('images', ('bar.png', open('bar.png', 'rb'), 'image/png'))]369 ('images', ('foo.png', open('foo.png', 'rb'), 'image/png')),370 ('images', ('bar.png', open('bar.png', 'rb'), 'image/png'))]371 >>> r = requests.post(url, files=multiple_files)372 >>> r.text373 {374 ...
118 unmodified lines
493 the resulting iterator object instead::494495 lines = r.iter_lines()496 # Save the first line for later or just skip it497498 first_line = next(lines)499500 for line in lines:501 print(line)502503.. _proxies:
6 unmodified lines
510511 import requests512513 proxies = {506 "http": "http://10.10.1.10:3128",507 "https": "http://10.10.1.10:1080",514 'http': 'http://10.10.1.10:3128',515 'https': 'http://10.10.1.10:1080',516 }517510 requests.get("http://example.org", proxies=proxies)518 requests.get('http://example.org', proxies=proxies)519520You can also configure proxies by setting the environment variables521``HTTP_PROXY`` and ``HTTPS_PROXY``.522523::524525 $ export HTTP_PROXY="http://10.10.1.10:3128"526 $ export HTTPS_PROXY="http://10.10.1.10:1080"527528 $ python529 >>> import requests521 >>> requests.get("http://example.org")530 >>> requests.get('http://example.org')531532To use HTTP Basic Auth with your proxy, use the `http://user:password@host/` syntax::533525 proxies = {526 "http": "http://user:pass@10.10.1.10:3128/",527 }534 proxies = {'http': 'http://user:pass@10.10.1.10:3128/'}535536To give a proxy for a specific scheme and host, use the537`scheme://hostname` form for the key. This will match for538any request to the given scheme and exact hostname.539540::541535 proxies = {536 "http://10.20.1.128": "http://10.10.1.10:5323",537 }542 proxies = {'http://10.20.1.128': 'http://10.10.1.10:5323'}543544Note that proxy URLs must include the scheme.545546.. _compliance:
56 unmodified lines
603604::605606 >>> commit_data = r.json()607608 >>> print(commit_data.keys())609 [u'committer', u'author', u'url', u'tree', u'sha', u'parents', u'message']610611 >>> print(commit_data[u'committer'])612 {u'date': u'2012-05-10T11:10:50-07:00', u'email': u'me@kennethreitz.com', u'name': u'Kenneth Reitz'}613614 >>> print(commit_data[u'message'])615 makin' history616617So far, so simple. Well, let's investigate the GitHub API a little bit. Now,
31 unmodified lines
649650 >>> r = requests.get('https://api.github.com/repos/kennethreitz/requests/issues/482')651 >>> r.status_code652 200653654 >>> issue = json.loads(r.text)655656 >>> print(issue[u'title'])657 Feature any http verb in docs658659 >>> print(issue[u'comments'])660 3661662Cool, we have three comments. Let's take a look at the last of them.
2 unmodified lines
665666 >>> r = requests.get(r.url + u'/comments')667 >>> r.status_code668 200669670 >>> comments = r.json()671672 >>> print(comments[0].keys())673 [u'body', u'url', u'created_at', u'updated_at', u'user', u'id']674675 >>> print(comments[2][u'body'])676 Probably in the "advanced" section677678Well, that seems like a silly place. Let's post a comment telling the poster
11 unmodified lines
690::691692 >>> body = json.dumps({u"body": u"Sounds great! I'll get right on it!"})693 >>> url = u"https://api.github.com/repos/kennethreitz/requests/issues/482/comments"694695 >>> r = requests.post(url=url, data=body)696 >>> r.status_code697 404698
4 unmodified lines
703::704705 >>> from requests.auth import HTTPBasicAuth706 >>> auth = HTTPBasicAuth('fake@example.com', 'not_a_real_password')707708 >>> r = requests.post(url=url, data=body, auth=auth)709 >>> r.status_code710 201711712 >>> content = r.json()713 >>> print(content[u'body'])714 Sounds great! I'll get right on it.715
5 unmodified lines
721::722723 >>> print(content[u"id"])724 5804413725726 >>> body = json.dumps({u"body": u"Sounds great! I'll get right on it once I feed my cat."})727 >>> url = u"https://api.github.com/repos/kennethreitz/requests/issues/comments/5804413"728729 >>> r = requests.patch(url=url, data=body, auth=auth)730 >>> r.status_code731 200732
112 unmodified lines
845 class Ssl3HttpAdapter(HTTPAdapter):846 """"Transport adapter" that allows us to use SSLv3."""847848 def init_poolmanager(self, connections, maxsize, block=False):830 self.poolmanager = PoolManager(num_pools=connections,831 maxsize=maxsize,832 block=block,833 ssl_version=ssl.PROTOCOL_SSLv3)849 self.poolmanager = PoolManager(850 num_pools=connections, maxsize=maxsize,851 block=block, ssl_version=ssl.PROTOCOL_SSLv3)852853.. _`described here`: http://www.kennethreitz.org/essays/the-future-of-python-http854.. _`urllib3`: https://github.com/shazow/urllib3855
58 unmodified lines
modified:docs/user/authentication.rst+2 added-2 removed
35 unmodified lines
36~~~~~~~~~~~~~~~~~~~~3738If no authentication method is given with the ``auth`` argument, Requests will39attempt to get the authentication credentials for the URL's hostname from the40user's netrc file.40user's netrc file. The netrc file overrides raw HTTP authentication headers41set with `headers=`.4243If credentials for the hostname are found, the request is sent with HTTP Basic44Auth.45
79 unmodified lines
125.. _requests_oauthlib: https://github.com/requests/requests-oauthlib126.. _Kerberos: https://github.com/requests/requests-kerberos127.. _NTLM: https://github.com/requests/requests-ntlm128.. _Requests organization: https://github.com/requests128
modified:docs/user/install.rst+12 added-20 removed
5 unmodified lines
6This part of the documentation covers the installation of Requests.7The first step to using any software package is getting it properly installed.8910Distribute & Pip11----------------10Pip Install Requests11--------------------1213Installing Requests is simple with `pip <https://pip.pypa.io>`_, just run14this in your terminal::13To install Requests, simply run this simple command in your terminal of choice::1415 $ pip install requests1618or, with `easy_install <http://pypi.python.org/pypi/setuptools>`_::17If you don't have `pip <https://pip.pypa.io>`_ installed (tisk tisk!),18`this Python installation guide <http://docs.python-guide.org/en/latest/starting/installation/>`_19can guide you through the process.2020 $ easy_install requests21Get the Source Code22-------------------2322But, you really `shouldn't do that <https://stackoverflow.com/questions/3220404/why-use-pip-over-easy-install>`_.232425Get the Code26------------2724Requests is actively developed on GitHub, where the code is25`always available <https://github.com/kennethreitz/requests>`_.2627You can either clone the public repository::2829 $ git clone git://github.com/kennethreitz/requests.git3035Download the `tarball <https://github.com/kennethreitz/requests/tarball/master>`_::31Or, download the `tarball <https://github.com/kennethreitz/requests/tarball/master>`_::3233 $ curl -OL https://github.com/kennethreitz/requests/tarball/master34 # optionally, zipball is also available (for Windows users).3539Or, download the `zipball <https://github.com/kennethreitz/requests/zipball/master>`_::36Once you have a copy of the source, you can embed it in your own Python37package, or install it into your site-packages easily::3841 $ curl -OL https://github.com/kennethreitz/requests/zipball/master424344Once you have a copy of the source, you can embed it in your Python package,45or install it into your site-packages easily::4639 $ python setup.py install
modified:docs/user/quickstart.rst+25 added-9 removed
35 unmodified lines
3637Requests' simple API means that all forms of HTTP request are as obvious. For38example, this is how you make an HTTP POST request::3940 >>> r = requests.post("http://httpbin.org/post", data = {"key":"value"})40 >>> r = requests.post('http://httpbin.org/post', data = {'key':'value'})4142Nice, right? What about the other HTTP request types: PUT, DELETE, HEAD and43OPTIONS? These are all just as simple::4445 >>> r = requests.put("http://httpbin.org/put", data = {"key":"value"})46 >>> r = requests.delete("http://httpbin.org/delete")47 >>> r = requests.head("http://httpbin.org/get")48 >>> r = requests.options("http://httpbin.org/get")45 >>> r = requests.put('http://httpbin.org/put', data = {'key':'value'})46 >>> r = requests.delete('http://httpbin.org/delete')47 >>> r = requests.head('http://httpbin.org/get')48 >>> r = requests.options('http://httpbin.org/get')4950That's all well and good, but it's also only the start of what Requests can51do.52
9 unmodified lines
62``key1=value1`` and ``key2=value2`` to ``httpbin.org/get``, you would use the63following code::6465 >>> payload = {'key1': 'value1', 'key2': 'value2'}66 >>> r = requests.get("http://httpbin.org/get", params=payload)66 >>> r = requests.get('http://httpbin.org/get', params=payload)6768You can see that the URL has been correctly encoded by printing the URL::6970 >>> print(r.url)
4 unmodified lines
7576You can also pass a list of items as a value::7778 >>> payload = {'key1': 'value1', 'key2': ['value2', 'value3']}7979 >>> r = requests.get("http://httpbin.org/get", params=payload)80 >>> r = requests.get('http://httpbin.org/get', params=payload)81 >>> print(r.url)82 http://httpbin.org/get?key1=value1&key2=value2&key2=value38384Response Content
2 unmodified lines
87We can read the content of the server's response. Consider the GitHub timeline88again::8990 >>> import requests9192 >>> r = requests.get('https://api.github.com/events')93 >>> r.text94 u'[{"repository":{"open_issues":0,"url":"https://github.com/...95
36 unmodified lines
132use the following code::133134 >>> from PIL import Image135 >>> from StringIO import StringIO136137 >>> i = Image.open(StringIO(r.content))138139140JSON Response Content
1 unmodified line
142143There's also a builtin JSON decoder, in case you're dealing with JSON data::144145 >>> import requests146147 >>> r = requests.get('https://api.github.com/events')148 >>> r.json()149 [{u'repository': {u'open_issues': 0, u'url': 'https://github.com/...150
15 unmodified lines
166server, you can access ``r.raw``. If you want to do this, make sure you set167``stream=True`` in your initial request. Once you do, you can do this::168169 >>> r = requests.get('https://api.github.com/events', stream=True)170171 >>> r.raw172 <requests.packages.urllib3.response.HTTPResponse object at 0x101194810>173174 >>> r.raw.read(10)175 '\x1f\x8b\x08\x00\x00\x00\x00\x00\x00\x03'176177In general, however, you should use a pattern like this to save what is being
16 unmodified lines
194``headers`` parameter.195196For example, we didn't specify our user-agent in the previous example::197192 >>> import json198 >>> url = 'https://api.github.com/some/endpoint'199 >>> headers = {'user-agent': 'my-app/0.0.1'}200201 >>> r = requests.get(url, headers=headers)202203Note: Custom headers are given less precedence than more specific sources of information. For instance:204200* Authorization headers will be overridden if credentials are passed via the ``auth`` parameter or are specified in a ``.netrc`` accessible in the environment.205* Authorization headers set with `headers=` will be overridden if credentials206 are specified in ``.netrc``, which in turn will be overridden by the ``auth=``207 parameter.208* Authorization headers will be removed if you get redirected off-host.209* Proxy-Authorization headers will be overridden by proxy credentials provided in the URL.210* Content-Length headers will be overridden when we can determine the length of the content.211
7 unmodified lines
219To do this, simply pass a dictionary to the ``data`` argument. Your220dictionary of data will automatically be form-encoded when the request is made::221222 >>> payload = {'key1': 'value1', 'key2': 'value2'}223224 >>> r = requests.post("http://httpbin.org/post", data=payload)225 >>> print(r.text)226 {227 ...
9 unmodified lines
237238For example, the GitHub API v3 accepts JSON-Encoded POST/PATCH data::239240 >>> import json241242 >>> url = 'https://api.github.com/some/endpoint'243 >>> payload = {'some': 'data'}244245 >>> r = requests.post(url, data=json.dumps(payload))
186 unmodified lines
432433For example, GitHub redirects all HTTP requests to HTTPS::434435 >>> r = requests.get('http://github.com')436437 >>> r.url438 'https://github.com/'439440 >>> r.status_code441 200442443 >>> r.history444 [<Response [301]>]445446447If you're using GET, OPTIONS, POST, PUT, PATCH or DELETE, you can disable448redirection handling with the ``allow_redirects`` parameter::449450 >>> r = requests.get('http://github.com', allow_redirects=False)451452 >>> r.status_code453 301454455 >>> r.history456 []457458If you're using HEAD, you can enable redirection as well::459460 >>> r = requests.head('http://github.com', allow_redirects=True)461462 >>> r.url463 'https://github.com/'464465 >>> r.history466 [<Response [301]>]467468
41 unmodified lines
modified:docs/api.rst+48 added-52 removed
23 unmodified lines
24.. autofunction:: put25.. autofunction:: patch26.. autofunction:: delete2728Exceptions29----------3031.. autoexception:: requests.RequestException32.. autoexception:: requests.ConnectionError33.. autoexception:: requests.HTTPError34.. autoexception:: requests.URLRequired35.. autoexception:: requests.TooManyRedirects36.. autoexception:: requests.ConnectTimeout37.. autoexception:: requests.ReadTimeout38.. autoexception:: requests.Timeout394041Request Sessions42----------------4344.. _sessionapi:4546.. autoclass:: Session47 :inherited-members:484950Lower-Level Classes30~~~~~~~~~~~~~~~~~~~51-------------------5253.. autoclass:: requests.Request54 :inherited-members:5556.. autoclass:: Response57 :inherited-members:5838Request Sessions39----------------5941.. autoclass:: Session60Lower-Lower-Level Classes61-------------------------6263.. autoclass:: requests.PreparedRequest64 :inherited-members:6566.. autoclass:: requests.adapters.HTTPAdapter67 :inherited-members:
5 unmodified lines
73.. autoclass:: requests.auth.HTTPBasicAuth74.. autoclass:: requests.auth.HTTPProxyAuth75.. autoclass:: requests.auth.HTTPDigestAuth7655Exceptions56~~~~~~~~~~7758.. autoexception:: requests.exceptions.RequestException59.. autoexception:: requests.exceptions.ConnectionError60.. autoexception:: requests.exceptions.HTTPError61.. autoexception:: requests.exceptions.URLRequired62.. autoexception:: requests.exceptions.TooManyRedirects63.. autoexception:: requests.exceptions.ConnectTimeout64.. autoexception:: requests.exceptions.ReadTimeout65.. autoexception:: requests.exceptions.Timeout7879Encodings80---------8168Status Code Lookup69~~~~~~~~~~~~~~~~~~82.. autofunction:: requests.utils.get_encodings_from_content83.. autofunction:: requests.utils.get_encoding_from_headers84.. autofunction:: requests.utils.get_unicode_from_response8571.. autofunction:: requests.codes8673::7475 >>> requests.codes['temporary_redirect']76 3077778 >>> requests.codes.teapot79 4188081 >>> requests.codes['\o/']82 2008387.. _api-cookies:8889Cookies87~~~~~~~90-------9192.. autofunction:: requests.utils.dict_from_cookiejar93.. autofunction:: requests.utils.cookiejar_from_dict94.. autofunction:: requests.utils.add_dict_to_cookiejar
4 unmodified lines
99.. autoclass:: requests.cookies.CookieConflictError100 :inherited-members:101102100Encodings101~~~~~~~~~103103.. autofunction:: requests.utils.get_encodings_from_content104.. autofunction:: requests.utils.get_encoding_from_headers105.. autofunction:: requests.utils.get_unicode_from_response104Status Code Lookup105------------------106107.. autofunction:: requests.codes108108Classes109~~~~~~~109::110111.. autoclass:: requests.Response112 :inherited-members:111 >>> requests.codes['temporary_redirect']112 307113114.. autoclass:: requests.Request115 :inherited-members:114 >>> requests.codes.teapot115 418116117.. autoclass:: requests.PreparedRequest118 :inherited-members:117 >>> requests.codes['\o/']118 200119120.. _sessionapi:120122.. autoclass:: requests.Session123 :inherited-members:121125.. autoclass:: requests.adapters.HTTPAdapter126 :inherited-members:127128122Migrating to 1.x123----------------124125This section details the main differences between 0.x and 1.x and is meant
50 unmodified lines
176177 import requests178 import logging179187 # these two lines enable debugging at httplib level (requests->urllib3->httplib)180 # Enabling debugging at http.client level (requests->urllib3->http.client)181 # you will see the REQUEST, including HEADERS and DATA, and RESPONSE with HEADERS but without DATA.182 # the only thing missing will be the response.body which is not logged.190 import httplib191 httplib.HTTPConnection.debuglevel = 1183 try: # for Python 3184 from http.client import HTTPConnection185 except ImportError:186 from httplib import HTTPConnection187 HTTPConnection.debuglevel = 1188189 logging.basicConfig() # you need to initialize logging, otherwise you will not see anything from requests190 logging.getLogger().setLevel(logging.DEBUG)191 requests_log = logging.getLogger("requests.packages.urllib3")
72 unmodified lines
modified:docs/conf.py+173 added-42 removed
1# -*- coding: utf-8 -*-2#3# Requests documentation build configuration file, created by4# sphinx-quickstart on Sun Feb 13 23:54:25 2011.4# sphinx-quickstart on Fri Feb 19 00:05:47 2016.5#6# This file is execfile()d with the current directory set to its containing dir.6# This file is execfile()d with the current directory set to its7# containing dir.8#9# Note that not all possible configuration values are present in this10# autogenerated file.11#12# All configuration values have a default; values that are commented out13# serve to show the default.1414import sys, os15import sys16import os1718# If extensions (or modules to document with autodoc) are in another directory,19# add these directories to sys.path here. If the directory is relative to the20# documentation root, use os.path.abspath to make it absolute, like shown here.21#sys.path.insert(0, os.path.abspath('.'))2223# Insert Requests' path into the system.24sys.path.insert(0, os.path.abspath('..'))25sys.path.insert(0, os.path.abspath('_themes'))2627import requests28from requests import __version__2923# -- General configuration -----------------------------------------------------3031# -- General configuration ------------------------------------------------3233# If your documentation needs a minimal Sphinx version, state it here.34#needs_sphinx = '1.0'3528# Add any Sphinx extension module names here, as strings. They can be extensions29# coming with Sphinx (named 'sphinx.ext.*') or your custom ones.36# Add any Sphinx extension module names here, as strings. They can be37# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom38# ones.39extensions = [40 'sphinx.ext.autodoc',41 'sphinx.ext.intersphinx',42 'sphinx.ext.todo',43 'sphinx.ext.viewcode',44]4546# Add any paths that contain templates here, relative to this directory.47templates_path = ['_templates']4838# The suffix of source filenames.49# The suffix(es) of source filenames.50# You can specify multiple suffix as a list of string:51# source_suffix = ['.rst', '.md']52source_suffix = '.rst'5354# The encoding of source files.55#source_encoding = 'utf-8-sig'
2 unmodified lines
58master_doc = 'index'5960# General information about the project.61project = u'Requests'49copyright = u'2015. A <a href="http://kennethreitz.com/pages/open-projects.html">Kenneth Reitz</a> Project'62copyright = u'2016. A <a href="http://kennethreitz.com/pages/open-projects.html">Kenneth Reitz</a> Project'63author = u'Kenneth Reitz'6465# The version info for the project you're documenting, acts as replacement for66# |version| and |release|, also used in various other places throughout the67# built documents.68#69# The short X.Y version.70version = __version__71# The full version, including alpha/beta/rc tags.58release = version72release = __version__7374# The language for content autogenerated by Sphinx. Refer to documentation75# for a list of supported languages.76#77# This is also used if you do content translation via gettext catalogs.78# Usually you set "language" from the command line for these cases.62#language = None79language = None8081# There are two options for replacing |today|: either, you set today to some82# non-false value, then it is used:83#today = ''
3 unmodified lines
87# List of patterns, relative to source directory, that match files and88# directories to ignore when looking for source files.89exclude_patterns = ['_build']9074# The reST default role (used for this markup: `text`) to use for all documents.91# The reST default role (used for this markup: `text`) to use for all92# documents.93#default_role = None9495# If true, '()' will be appended to :func: etc. cross-reference text.78#add_function_parentheses = True96add_function_parentheses = False9798# If true, the current module name will be prepended to all description99# unit titles (such as .. function::).82#add_module_names = True100add_module_names = True101102# If true, sectionauthor and moduleauthor directives will be shown in the103# output. They are ignored by default.104#show_authors = False
3 unmodified lines
108109# A list of ignored prefixes for module index sorting.110#modindex_common_prefix = []111112# If true, keep warnings as "system message" paragraphs in the built documents.113#keep_warnings = False11495# -- Options for HTML output ---------------------------------------------------115# If true, `todo` and `todoList` produce output, else they produce nothing.116todo_include_todos = True117118119# -- Options for HTML output ----------------------------------------------120121# The theme to use for HTML and HTML Help pages. See the documentation for122# a list of builtin themes.99html_theme = 'default'123html_theme = 'alabaster'124125# Theme options are theme-specific and customize the look and feel of a theme126# further. For a list of options available for each theme, see the127# documentation.104#html_theme_options = {}128html_theme_options = {129 'show_powered_by': False,130 'github_user': 'kennethreitz',131 'github_repo': 'requests',132 'github_banner': True,133 'show_related': False134}135136# Add any paths that contain custom themes here, relative to this directory.137#html_theme_path = []138
7 unmodified lines
146# The name of an image file (relative to this directory) to place at the top147# of the sidebar.148#html_logo = None149120150# The name of an image file (within the static path) to use as favicon of the151# docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32152# pixels large.153#html_favicon = None
2 unmodified lines
156# relative to this directory. They are copied after the builtin static files,157# so a file named "default.css" will overwrite the builtin "default.css".158html_static_path = ['_static']159160# Add any extra paths that contain custom files (such as robots.txt or161# .htaccess) here, relative to this directory. These files are copied162# directly to the root of the documentation.163#html_extra_path = []164165# If not '', a 'Last updated on:' timestamp is inserted at every page bottom,166# using the given strftime format.167#html_last_updated_fmt = '%b %d, %Y'168169# If true, SmartyPants will be used to convert quotes and dashes to170# typographically correct entities.137#html_use_smartypants = True171html_use_smartypants = False172173# Custom sidebar templates, maps document names to template names.174html_sidebars = {141 'index': ['sidebarintro.html', 'sourcelink.html', 'searchbox.html'],175 'index': ['sidebarintro.html', 'sourcelink.html', 'searchbox.html',176 'hacks.html'],177 '**': ['sidebarlogo.html', 'localtoc.html', 'relations.html',143 'sourcelink.html', 'searchbox.html']178 'sourcelink.html', 'searchbox.html', 'hacks.html']179}180181# Additional templates that should be rendered to pages, maps page names to182# template names.
14 unmodified lines
197# If true, "Created using Sphinx" is shown in the HTML footer. Default is True.198html_show_sphinx = False199200# If true, "(C) Copyright ..." is shown in the HTML footer. Default is True.166#html_show_copyright = True201html_show_copyright = True202203# If true, an OpenSearch description file will be output, and all pages will204# contain a <link> tag referring to it. The value of this option must be the205# base URL from which the finished HTML is served.
1 unmodified line
207208# This is the file name suffix for HTML files (e.g. ".xhtml").209#html_file_suffix = None210211# Language to be used for generating the HTML full-text search index.212# Sphinx supports the following languages:213# 'da', 'de', 'en', 'es', 'fi', 'fr', 'hu', 'it', 'ja'214# 'nl', 'no', 'pt', 'ro', 'ru', 'sv', 'tr'215#html_search_language = 'en'216217# A dictionary with options for the search language support, empty by default.218# Now only 'ja' uses this config value219#html_search_options = {'type': 'default'}220221# The name of a javascript file (relative to the configuration directory) that222# implements a search results scorer. If empty, the default will be used.223#html_search_scorer = 'scorer.js'224225# Output file base name for HTML help builder.226htmlhelp_basename = 'Requestsdoc'227228# -- Options for LaTeX output ---------------------------------------------229180# -- Options for LaTeX output --------------------------------------------------230latex_elements = {231# The paper size ('letterpaper' or 'a4paper').232#'papersize': 'letterpaper',233182# The paper size ('letter' or 'a4').183#latex_paper_size = 'letter'184234# The font size ('10pt', '11pt' or '12pt').186#latex_font_size = '10pt'235#'pointsize': '10pt',236237# Additional stuff for the LaTeX preamble.238#'preamble': '',239240# Latex figure (float) alignment241#'figure_align': 'htbp',242}243244# Grouping the document tree into LaTeX files. List of tuples189# (source start file, target name, title, author, documentclass [howto/manual]).245# (source start file, target name, title,246# author, documentclass [howto, manual, or own class]).247latex_documents = [191 ('index', 'Requests.tex', u'Requests Documentation',192 u'Kenneth Reitz', 'manual'),248 (master_doc, 'Requests.tex', u'Requests Documentation',249 u'Kenneth Reitz', 'manual'),250]251252# The name of an image file (relative to this directory) to place at the top of253# the title page.
8 unmodified lines
262263# If true, show URL addresses after external links.264#latex_show_urls = False265209# Additional stuff for the LaTeX preamble.210#latex_preamble = ''211266# Documents to append as an appendix to all manuals.267#latex_appendices = []268269# If false, no module index is generated.270#latex_domain_indices = True271272219# -- Options for manual page output --------------------------------------------273# -- Options for manual page output ---------------------------------------274275# One entry per manual page. List of tuples276# (source start file, name, description, authors, manual section).277man_pages = [224 ('index', 'requests', u'Requests Documentation',225 [u'Kenneth Reitz'], 1)278 (master_doc, 'requests', u'Requests Documentation',279 [author], 1)280]281282# If true, show URL addresses after external links.283#man_show_urls = False284231# -- Options for Texinfo output ------------------------------------------------285286# -- Options for Texinfo output -------------------------------------------287288# Grouping the document tree into Texinfo files. List of tuples289# (source start file, target name, title, author,290# dir menu entry, description, category)291texinfo_documents = [237 ('index', 'Requests', u'Requests Documentation', u'Kenneth Reitz',238 'Requests', 'One line description of project.', 'Miscellaneous'),292 (master_doc, 'Requests', u'Requests Documentation',293 author, 'Requests', 'One line description of project.',294 'Miscellaneous'),295]296297# Documents to append as an appendix to all manuals.242texinfo_appendices = []298#texinfo_appendices = []299244sys.path.append(os.path.abspath('_themes'))245html_theme_path = ['_themes']246html_theme = 'kr'300# If false, no module index is generated.301#texinfo_domain_indices = True302303# How to display URL addresses: 'footnote', 'no', or 'inline'.304#texinfo_show_urls = 'footnote'305306# If true, do not generate a @detailmenu in the "Top" node's menu.307#texinfo_no_detailmenu = False308309310# -- Options for Epub output ----------------------------------------------311312# Bibliographic Dublin Core info.313epub_title = project314epub_author = author315epub_publisher = author316epub_copyright = copyright317318# The basename for the epub file. It defaults to the project name.319#epub_basename = project320321# The HTML theme for the epub output. Since the default themes are not322# optimized for small screen space, using the same theme for HTML and epub323# output is usually not wise. This defaults to 'epub', a theme designed to save324# visual space.325#epub_theme = 'epub'326327# The language of the text. It defaults to the language option328# or 'en' if the language is not set.329#epub_language = ''330331# The scheme of the identifier. Typical schemes are ISBN or URL.332#epub_scheme = ''333334# The unique identifier of the text. This can be a ISBN number335# or the project homepage.336#epub_identifier = ''337338# A unique identification for the text.339#epub_uid = ''340341# A tuple containing the cover image and cover page html template filenames.342#epub_cover = ()343344# A sequence of (type, uri, title) tuples for the guide element of content.opf.345#epub_guide = ()346347# HTML files that should be inserted before the pages created by sphinx.348# The format is a list of tuples containing the path and title.349#epub_pre_files = []350351# HTML files that should be inserted after the pages created by sphinx.352# The format is a list of tuples containing the path and title.353#epub_post_files = []354355# A list of files that should not be packed into the epub file.356epub_exclude_files = ['search.html']357358# The depth of the table of contents in toc.ncx.359#epub_tocdepth = 3360361# Allow duplicate toc entries.362#epub_tocdup = True363364# Choose between 'default' and 'includehidden'.365#epub_tocscope = 'default'366367# Fix unsupported image types using the Pillow.368#epub_fix_images = False369370# Scale large images.371#epub_max_image_width = 0372373# How to display URL addresses: 'footnote', 'no', or 'inline'.374#epub_show_urls = 'inline'375376# If false, no index is generated.377#epub_use_index = True378379intersphinx_mapping = {'urllib3': ('http://urllib3.readthedocs.org/en/latest', None)}
modified:docs/index.rst+41 added-35 removed
6 unmodified lines
7=========================89Release v\ |version|. (:ref:`Installation <install>`)1011Requests is an :ref:`Apache2 Licensed <apache2>` HTTP library, written in12Python, for human beings.11Requests is the only *Non-GMO* HTTP library for Python, safe for human12consumption.1314Python's standard **urllib2** module provides most of15the HTTP capabilities you need, but the API is thoroughly **broken**.16It was built for a different time — and a different web. It requires an17*enormous* amount of work (even method overrides) to perform the simplest of18tasks.14**Warning:** Recreational use of other HTTP libraries may result in dangerous side-effects,15including: security vulnerabilities, verbose code, reinventing the wheel,16constantly reading documentation, depression, headaches, or even death.1720Things shouldn’t be this way. Not in Python.18Behold, the power of Requests::1922::2320 >>> r = requests.get('https://api.github.com/user', auth=('user', 'pass'))21 >>> r.status_code22 20023 >>> r.headers['content-type']
4 unmodified lines
28 u'{"type":"User"...'29 >>> r.json()30 {u'private_gists': 419, u'total_private_repos': 77, ...}3136See `similar code, without Requests <https://gist.github.com/973705>`_.32See `similar code, sans Requests <https://gist.github.com/973705>`_.3338Requests takes all of the work out of Python HTTP/1.1 — making your integration39with web services seamless. There's no need to manually add query strings to40your URLs, or to form-encode your POST data. Keep-alive and HTTP connection41pooling are 100% automatic, powered by `urllib3 <https://github.com/shazow/urllib3>`_,3435Requests allows you to send *organic, grass-fed* HTTP/1.1 requests, without the36need for manual labor. There's no need to manually add query strings to your37URLs, or to form-encode your POST data. Keep-alive and HTTP connection pooling38are 100% automatic, powered by `urllib3 <https://github.com/shazow/urllib3>`_,39which is embedded within Requests.4041User Testimonials42-----------------4345Testimonials46------------4744Her Majesty's Government, Amazon, Google, Twilio, Runscope, Mozilla, Heroku,45PayPal, NPR, Obama for America, Transifex, Native Instruments, The Washington50Post, Twitter, SoundCloud, Kippt, Readability, Sony, and Federal US Institutions that prefer to be unnamed51use Requests internally. It has been downloaded over 60,000,000 times from PyPI.46Post, Twitter, SoundCloud, Kippt, Readability, Sony, and Federal U.S.47Institutions that prefer to be unnamed claim to use Requests internally.4849**Armin Ronacher**50 Requests is the perfect example how beautiful an API can be with the51 right level of abstraction.
9 unmodified lines
61**Kenny Meyers**62 Python HTTP: When in doubt, or when not in doubt, use Requests. Beautiful,63 simple, Pythonic.6465Requests is one of the most downloaded Python packages of all time, pulling in66over 7,000,000 downloads every month. All the cool kids are doing it!6770Feature Support71---------------68Supported Features69------------------7071Requests is ready for today's web.7273- International Domains and URLs
2 unmodified lines
76- Browser-style SSL Verification77- Basic/Digest Authentication78- Elegant Key/Value Cookies79- Automatic Decompression80- Automatic Content Decoding81- Unicode Response Bodies82- Multipart File Uploads83- HTTP(S) Proxy Support84- Connection Timeouts85- Streaming Downloads85- ``.netrc`` support86- Python 2.6—3.487- Thread-safe.86- ``.netrc`` Support87- Chunked Requests88- Thread-safety8990Requests supports Python 2.6 — 3.5, and runs great on PyPy.9190User Guide91----------9293The User Guide94--------------9596This part of the documentation, which is mostly prose, begins with some97background information about Requests, then focuses on step-by-step98instructions for getting the most out of Requests.99
6 unmodified lines
106 user/advanced107 user/authentication108109107Community Guide108-----------------110The Community Guide111-------------------112113This part of the documentation, which is mostly prose, details the114Requests ecosystem and community.115
7 unmodified lines
123 community/vulnerabilities124 community/updates125 community/release-process126124API Documentation125-----------------127The API Documentation / Guide128-----------------------------129127If you are looking for information on a specific function, class or method,130If you are looking for information on a specific function, class, or method,131this part of the documentation is for you.132133.. toctree::134 :maxdepth: 2135136 api137138136Contributor Guide137-----------------139The Contributor Guide140---------------------141142If you want to contribute to the project, this part of the documentation is for143you.144145.. toctree::143 :maxdepth: 1146 :maxdepth: 3147148 dev/contributing149 dev/philosophy150 dev/todo151 dev/authors152153There are no more guides. You are now guideless.154Good luck.
modified:docs/make.bat+263 added-190 removed
1@ECHO OFF23REM Command file for Sphinx documentation45if "%SPHINXBUILD%" == "" (6 set SPHINXBUILD=sphinx-build7)8set BUILDDIR=_build9set ALLSPHINXOPTS=-d %BUILDDIR%/doctrees %SPHINXOPTS% .10set I18NSPHINXOPTS=%SPHINXOPTS% .11if NOT "%PAPER%" == "" (12 set ALLSPHINXOPTS=-D latex_paper_size=%PAPER% %ALLSPHINXOPTS%13 set I18NSPHINXOPTS=-D latex_paper_size=%PAPER% %I18NSPHINXOPTS%14)1516if "%1" == "" goto help1718if "%1" == "help" (19 :help20 echo.Please use `make ^<target^>` where ^<target^> is one of21 echo. html to make standalone HTML files22 echo. dirhtml to make HTML files named index.html in directories23 echo. singlehtml to make a single large HTML file24 echo. pickle to make pickle files25 echo. json to make JSON files26 echo. htmlhelp to make HTML files and a HTML help project27 echo. qthelp to make HTML files and a qthelp project28 echo. devhelp to make HTML files and a Devhelp project29 echo. epub to make an epub30 echo. latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter31 echo. text to make text files32 echo. man to make manual pages33 echo. texinfo to make Texinfo files34 echo. gettext to make PO message catalogs35 echo. changes to make an overview over all changed/added/deprecated items36 echo. linkcheck to check all external links for integrity37 echo. doctest to run all doctests embedded in the documentation if enabled38 goto end39)4041if "%1" == "clean" (42 for /d %%i in (%BUILDDIR%\*) do rmdir /q /s %%i43 del /q /s %BUILDDIR%\*44 goto end45)4647if "%1" == "html" (48 %SPHINXBUILD% -b html %ALLSPHINXOPTS% %BUILDDIR%/html49 if errorlevel 1 exit /b 150 echo.51 echo.Build finished. The HTML pages are in %BUILDDIR%/html.52 goto end53)5455if "%1" == "dirhtml" (56 %SPHINXBUILD% -b dirhtml %ALLSPHINXOPTS% %BUILDDIR%/dirhtml57 if errorlevel 1 exit /b 158 echo.59 echo.Build finished. The HTML pages are in %BUILDDIR%/dirhtml.60 goto end61)6263if "%1" == "singlehtml" (64 %SPHINXBUILD% -b singlehtml %ALLSPHINXOPTS% %BUILDDIR%/singlehtml65 if errorlevel 1 exit /b 166 echo.67 echo.Build finished. The HTML pages are in %BUILDDIR%/singlehtml.68 goto end69)7071if "%1" == "pickle" (72 %SPHINXBUILD% -b pickle %ALLSPHINXOPTS% %BUILDDIR%/pickle73 if errorlevel 1 exit /b 174 echo.75 echo.Build finished; now you can process the pickle files.76 goto end77)7879if "%1" == "json" (80 %SPHINXBUILD% -b json %ALLSPHINXOPTS% %BUILDDIR%/json81 if errorlevel 1 exit /b 182 echo.83 echo.Build finished; now you can process the JSON files.84 goto end85)8687if "%1" == "htmlhelp" (88 %SPHINXBUILD% -b htmlhelp %ALLSPHINXOPTS% %BUILDDIR%/htmlhelp89 if errorlevel 1 exit /b 190 echo.91 echo.Build finished; now you can run HTML Help Workshop with the ^92.hhp project file in %BUILDDIR%/htmlhelp.93 goto end94)9596if "%1" == "qthelp" (97 %SPHINXBUILD% -b qthelp %ALLSPHINXOPTS% %BUILDDIR%/qthelp98 if errorlevel 1 exit /b 199 echo.100 echo.Build finished; now you can run "qcollectiongenerator" with the ^101.qhcp project file in %BUILDDIR%/qthelp, like this:102 echo.^> qcollectiongenerator %BUILDDIR%\qthelp\Requests.qhcp103 echo.To view the help file:104 echo.^> assistant -collectionFile %BUILDDIR%\qthelp\Requests.ghc105 goto end106)107108if "%1" == "devhelp" (109 %SPHINXBUILD% -b devhelp %ALLSPHINXOPTS% %BUILDDIR%/devhelp110 if errorlevel 1 exit /b 1111 echo.112 echo.Build finished.113 goto end114)115116if "%1" == "epub" (117 %SPHINXBUILD% -b epub %ALLSPHINXOPTS% %BUILDDIR%/epub118 if errorlevel 1 exit /b 1119 echo.120 echo.Build finished. The epub file is in %BUILDDIR%/epub.121 goto end122)123124if "%1" == "latex" (125 %SPHINXBUILD% -b latex %ALLSPHINXOPTS% %BUILDDIR%/latex126 if errorlevel 1 exit /b 1127 echo.128 echo.Build finished; the LaTeX files are in %BUILDDIR%/latex.129 goto end130)131132if "%1" == "text" (133 %SPHINXBUILD% -b text %ALLSPHINXOPTS% %BUILDDIR%/text134 if errorlevel 1 exit /b 1135 echo.136 echo.Build finished. The text files are in %BUILDDIR%/text.137 goto end138)139140if "%1" == "man" (141 %SPHINXBUILD% -b man %ALLSPHINXOPTS% %BUILDDIR%/man142 if errorlevel 1 exit /b 1143 echo.144 echo.Build finished. The manual pages are in %BUILDDIR%/man.145 goto end146)147148if "%1" == "texinfo" (149 %SPHINXBUILD% -b texinfo %ALLSPHINXOPTS% %BUILDDIR%/texinfo150 if errorlevel 1 exit /b 1151 echo.152 echo.Build finished. The Texinfo files are in %BUILDDIR%/texinfo.153 goto end154)155156if "%1" == "gettext" (157 %SPHINXBUILD% -b gettext %I18NSPHINXOPTS% %BUILDDIR%/locale158 if errorlevel 1 exit /b 1159 echo.160 echo.Build finished. The message catalogs are in %BUILDDIR%/locale.161 goto end162)163164if "%1" == "changes" (165 %SPHINXBUILD% -b changes %ALLSPHINXOPTS% %BUILDDIR%/changes166 if errorlevel 1 exit /b 1167 echo.168 echo.The overview file is in %BUILDDIR%/changes.169 goto end170)171172if "%1" == "linkcheck" (173 %SPHINXBUILD% -b linkcheck %ALLSPHINXOPTS% %BUILDDIR%/linkcheck174 if errorlevel 1 exit /b 1175 echo.176 echo.Link check complete; look for any errors in the above output ^177or in %BUILDDIR%/linkcheck/output.txt.178 goto end179)180181if "%1" == "doctest" (182 %SPHINXBUILD% -b doctest %ALLSPHINXOPTS% %BUILDDIR%/doctest183 if errorlevel 1 exit /b 1184 echo.185 echo.Testing of doctests in the sources finished, look at the ^186results in %BUILDDIR%/doctest/output.txt.187 goto end188)189190:end1@ECHO OFF23REM Command file for Sphinx documentation45if "%SPHINXBUILD%" == "" (6 set SPHINXBUILD=sphinx-build7)8set BUILDDIR=_build9set ALLSPHINXOPTS=-d %BUILDDIR%/doctrees %SPHINXOPTS% .10set I18NSPHINXOPTS=%SPHINXOPTS% .11if NOT "%PAPER%" == "" (12 set ALLSPHINXOPTS=-D latex_paper_size=%PAPER% %ALLSPHINXOPTS%13 set I18NSPHINXOPTS=-D latex_paper_size=%PAPER% %I18NSPHINXOPTS%14)1516if "%1" == "" goto help1718if "%1" == "help" (19 :help20 echo.Please use `make ^<target^>` where ^<target^> is one of21 echo. html to make standalone HTML files22 echo. dirhtml to make HTML files named index.html in directories23 echo. singlehtml to make a single large HTML file24 echo. pickle to make pickle files25 echo. json to make JSON files26 echo. htmlhelp to make HTML files and a HTML help project27 echo. qthelp to make HTML files and a qthelp project28 echo. devhelp to make HTML files and a Devhelp project29 echo. epub to make an epub30 echo. latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter31 echo. text to make text files32 echo. man to make manual pages33 echo. texinfo to make Texinfo files34 echo. gettext to make PO message catalogs35 echo. changes to make an overview over all changed/added/deprecated items36 echo. xml to make Docutils-native XML files37 echo. pseudoxml to make pseudoxml-XML files for display purposes38 echo. linkcheck to check all external links for integrity39 echo. doctest to run all doctests embedded in the documentation if enabled40 echo. coverage to run coverage check of the documentation if enabled41 goto end42)4344if "%1" == "clean" (45 for /d %%i in (%BUILDDIR%\*) do rmdir /q /s %%i46 del /q /s %BUILDDIR%\*47 goto end48)495051REM Check if sphinx-build is available and fallback to Python version if any52%SPHINXBUILD% 1>NUL 2>NUL53if errorlevel 9009 goto sphinx_python54goto sphinx_ok5556:sphinx_python5758set SPHINXBUILD=python -m sphinx.__init__59%SPHINXBUILD% 2> nul60if errorlevel 9009 (61 echo.62 echo.The 'sphinx-build' command was not found. Make sure you have Sphinx63 echo.installed, then set the SPHINXBUILD environment variable to point64 echo.to the full path of the 'sphinx-build' executable. Alternatively you65 echo.may add the Sphinx directory to PATH.66 echo.67 echo.If you don't have Sphinx installed, grab it from68 echo.http://sphinx-doc.org/69 exit /b 170)7172:sphinx_ok737475if "%1" == "html" (76 %SPHINXBUILD% -b html %ALLSPHINXOPTS% %BUILDDIR%/html77 if errorlevel 1 exit /b 178 echo.79 echo.Build finished. The HTML pages are in %BUILDDIR%/html.80 goto end81)8283if "%1" == "dirhtml" (84 %SPHINXBUILD% -b dirhtml %ALLSPHINXOPTS% %BUILDDIR%/dirhtml85 if errorlevel 1 exit /b 186 echo.87 echo.Build finished. The HTML pages are in %BUILDDIR%/dirhtml.88 goto end89)9091if "%1" == "singlehtml" (92 %SPHINXBUILD% -b singlehtml %ALLSPHINXOPTS% %BUILDDIR%/singlehtml93 if errorlevel 1 exit /b 194 echo.95 echo.Build finished. The HTML pages are in %BUILDDIR%/singlehtml.96 goto end97)9899if "%1" == "pickle" (100 %SPHINXBUILD% -b pickle %ALLSPHINXOPTS% %BUILDDIR%/pickle101 if errorlevel 1 exit /b 1102 echo.103 echo.Build finished; now you can process the pickle files.104 goto end105)106107if "%1" == "json" (108 %SPHINXBUILD% -b json %ALLSPHINXOPTS% %BUILDDIR%/json109 if errorlevel 1 exit /b 1110 echo.111 echo.Build finished; now you can process the JSON files.112 goto end113)114115if "%1" == "htmlhelp" (116 %SPHINXBUILD% -b htmlhelp %ALLSPHINXOPTS% %BUILDDIR%/htmlhelp117 if errorlevel 1 exit /b 1118 echo.119 echo.Build finished; now you can run HTML Help Workshop with the ^120.hhp project file in %BUILDDIR%/htmlhelp.121 goto end122)123124if "%1" == "qthelp" (125 %SPHINXBUILD% -b qthelp %ALLSPHINXOPTS% %BUILDDIR%/qthelp126 if errorlevel 1 exit /b 1127 echo.128 echo.Build finished; now you can run "qcollectiongenerator" with the ^129.qhcp project file in %BUILDDIR%/qthelp, like this:130 echo.^> qcollectiongenerator %BUILDDIR%\qthelp\Requests.qhcp131 echo.To view the help file:132 echo.^> assistant -collectionFile %BUILDDIR%\qthelp\Requests.ghc133 goto end134)135136if "%1" == "devhelp" (137 %SPHINXBUILD% -b devhelp %ALLSPHINXOPTS% %BUILDDIR%/devhelp138 if errorlevel 1 exit /b 1139 echo.140 echo.Build finished.141 goto end142)143144if "%1" == "epub" (145 %SPHINXBUILD% -b epub %ALLSPHINXOPTS% %BUILDDIR%/epub146 if errorlevel 1 exit /b 1147 echo.148 echo.Build finished. The epub file is in %BUILDDIR%/epub.149 goto end150)151152if "%1" == "latex" (153 %SPHINXBUILD% -b latex %ALLSPHINXOPTS% %BUILDDIR%/latex154 if errorlevel 1 exit /b 1155 echo.156 echo.Build finished; the LaTeX files are in %BUILDDIR%/latex.157 goto end158)159160if "%1" == "latexpdf" (161 %SPHINXBUILD% -b latex %ALLSPHINXOPTS% %BUILDDIR%/latex162 cd %BUILDDIR%/latex163 make all-pdf164 cd %~dp0165 echo.166 echo.Build finished; the PDF files are in %BUILDDIR%/latex.167 goto end168)169170if "%1" == "latexpdfja" (171 %SPHINXBUILD% -b latex %ALLSPHINXOPTS% %BUILDDIR%/latex172 cd %BUILDDIR%/latex173 make all-pdf-ja174 cd %~dp0175 echo.176 echo.Build finished; the PDF files are in %BUILDDIR%/latex.177 goto end178)179180if "%1" == "text" (181 %SPHINXBUILD% -b text %ALLSPHINXOPTS% %BUILDDIR%/text182 if errorlevel 1 exit /b 1183 echo.184 echo.Build finished. The text files are in %BUILDDIR%/text.185 goto end186)187188if "%1" == "man" (189 %SPHINXBUILD% -b man %ALLSPHINXOPTS% %BUILDDIR%/man190 if errorlevel 1 exit /b 1191 echo.192 echo.Build finished. The manual pages are in %BUILDDIR%/man.193 goto end194)195196if "%1" == "texinfo" (197 %SPHINXBUILD% -b texinfo %ALLSPHINXOPTS% %BUILDDIR%/texinfo198 if errorlevel 1 exit /b 1199 echo.200 echo.Build finished. The Texinfo files are in %BUILDDIR%/texinfo.201 goto end202)203204if "%1" == "gettext" (205 %SPHINXBUILD% -b gettext %I18NSPHINXOPTS% %BUILDDIR%/locale206 if errorlevel 1 exit /b 1207 echo.208 echo.Build finished. The message catalogs are in %BUILDDIR%/locale.209 goto end210)211212if "%1" == "changes" (213 %SPHINXBUILD% -b changes %ALLSPHINXOPTS% %BUILDDIR%/changes214 if errorlevel 1 exit /b 1215 echo.216 echo.The overview file is in %BUILDDIR%/changes.217 goto end218)219220if "%1" == "linkcheck" (221 %SPHINXBUILD% -b linkcheck %ALLSPHINXOPTS% %BUILDDIR%/linkcheck222 if errorlevel 1 exit /b 1223 echo.224 echo.Link check complete; look for any errors in the above output ^225or in %BUILDDIR%/linkcheck/output.txt.226 goto end227)228229if "%1" == "doctest" (230 %SPHINXBUILD% -b doctest %ALLSPHINXOPTS% %BUILDDIR%/doctest231 if errorlevel 1 exit /b 1232 echo.233 echo.Testing of doctests in the sources finished, look at the ^234results in %BUILDDIR%/doctest/output.txt.235 goto end236)237238if "%1" == "coverage" (239 %SPHINXBUILD% -b coverage %ALLSPHINXOPTS% %BUILDDIR%/coverage240 if errorlevel 1 exit /b 1241 echo.242 echo.Testing of coverage in the sources finished, look at the ^243results in %BUILDDIR%/coverage/python.txt.244 goto end245)246247if "%1" == "xml" (248 %SPHINXBUILD% -b xml %ALLSPHINXOPTS% %BUILDDIR%/xml249 if errorlevel 1 exit /b 1250 echo.251 echo.Build finished. The XML files are in %BUILDDIR%/xml.252 goto end253)254255if "%1" == "pseudoxml" (256 %SPHINXBUILD% -b pseudoxml %ALLSPHINXOPTS% %BUILDDIR%/pseudoxml257 if errorlevel 1 exit /b 1258 echo.259 echo.Build finished. The pseudo-XML files are in %BUILDDIR%/pseudoxml.260 goto end261)262263:end
modified:docs/Makefile+67 added-4 removed
5 unmodified lines
6SPHINXBUILD = sphinx-build7PAPER =8BUILDDIR = _build910# User-friendly check for sphinx-build11ifeq ($(shell which $(SPHINXBUILD) >/dev/null 2>&1; echo $$?), 1)12$(error The '$(SPHINXBUILD)' command was not found. Make sure you have Sphinx installed, then set the SPHINXBUILD environment variable to point to the full path of the '$(SPHINXBUILD)' executable. Alternatively you can add the directory with the executable to your PATH. If you don't have Sphinx installed, grab it from http://sphinx-doc.org/)13endif1415# Internal variables.16PAPEROPT_a4 = -D latex_paper_size=a417PAPEROPT_letter = -D latex_paper_size=letter18ALLSPHINXOPTS = -d $(BUILDDIR)/doctrees $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) .19# the i18n builder cannot share the environment and doctrees with the others20I18NSPHINXOPTS = $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) .2117.PHONY: help clean html dirhtml singlehtml pickle json htmlhelp qthelp devhelp epub latex latexpdf text man changes linkcheck doctest gettext1822.PHONY: help23help:24 @echo "Please use \`make <target>' where <target> is one of"25 @echo " html to make standalone HTML files"26 @echo " dirhtml to make HTML files named index.html in directories"
1 unmodified line
28 @echo " pickle to make pickle files"29 @echo " json to make JSON files"30 @echo " htmlhelp to make HTML files and a HTML help project"31 @echo " qthelp to make HTML files and a qthelp project"32 @echo " applehelp to make an Apple Help Book"33 @echo " devhelp to make HTML files and a Devhelp project"34 @echo " epub to make an epub"35 @echo " latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter"36 @echo " latexpdf to make LaTeX files and run them through pdflatex"37 @echo " latexpdfja to make LaTeX files and run them through platex/dvipdfmx"38 @echo " text to make text files"39 @echo " man to make manual pages"40 @echo " texinfo to make Texinfo files"41 @echo " info to make Texinfo files and run them through makeinfo"42 @echo " gettext to make PO message catalogs"43 @echo " changes to make an overview of all changed/added/deprecated items"44 @echo " xml to make Docutils-native XML files"45 @echo " pseudoxml to make pseudoxml-XML files for display purposes"46 @echo " linkcheck to check all external links for integrity"47 @echo " doctest to run all doctests embedded in the documentation (if enabled)"48 @echo " coverage to run coverage check of the documentation (if enabled)"4950.PHONY: clean51clean:42 -rm -rf $(BUILDDIR)/*52 rm -rf $(BUILDDIR)/*5354.PHONY: html55html:56 $(SPHINXBUILD) -b html $(ALLSPHINXOPTS) $(BUILDDIR)/html57 @echo58 @echo "Build finished. The HTML pages are in $(BUILDDIR)/html."5960.PHONY: dirhtml61dirhtml:62 $(SPHINXBUILD) -b dirhtml $(ALLSPHINXOPTS) $(BUILDDIR)/dirhtml63 @echo64 @echo "Build finished. The HTML pages are in $(BUILDDIR)/dirhtml."6566.PHONY: singlehtml67singlehtml:68 $(SPHINXBUILD) -b singlehtml $(ALLSPHINXOPTS) $(BUILDDIR)/singlehtml69 @echo70 @echo "Build finished. The HTML page is in $(BUILDDIR)/singlehtml."7172.PHONY: pickle73pickle:74 $(SPHINXBUILD) -b pickle $(ALLSPHINXOPTS) $(BUILDDIR)/pickle75 @echo76 @echo "Build finished; now you can process the pickle files."7778.PHONY: json79json:80 $(SPHINXBUILD) -b json $(ALLSPHINXOPTS) $(BUILDDIR)/json81 @echo82 @echo "Build finished; now you can process the JSON files."8384.PHONY: htmlhelp85htmlhelp:86 $(SPHINXBUILD) -b htmlhelp $(ALLSPHINXOPTS) $(BUILDDIR)/htmlhelp87 @echo88 @echo "Build finished; now you can run HTML Help Workshop with the" \89 ".hhp project file in $(BUILDDIR)/htmlhelp."9091.PHONY: qthelp92qthelp:93 $(SPHINXBUILD) -b qthelp $(ALLSPHINXOPTS) $(BUILDDIR)/qthelp94 @echo95 @echo "Build finished; now you can run "qcollectiongenerator" with the" \
1 unmodified line
97 @echo "# qcollectiongenerator $(BUILDDIR)/qthelp/Requests.qhcp"98 @echo "To view the help file:"99 @echo "# assistant -collectionFile $(BUILDDIR)/qthelp/Requests.qhc"100101.PHONY: applehelp102applehelp:103 $(SPHINXBUILD) -b applehelp $(ALLSPHINXOPTS) $(BUILDDIR)/applehelp104 @echo105 @echo "Build finished. The help book is in $(BUILDDIR)/applehelp."106 @echo "N.B. You won't be able to view it unless you put it in" \107 "~/Library/Documentation/Help or install it in your application" \108 "bundle."109110.PHONY: devhelp111devhelp:112 $(SPHINXBUILD) -b devhelp $(ALLSPHINXOPTS) $(BUILDDIR)/devhelp113 @echo114 @echo "Build finished."
1 unmodified line
116 @echo "# mkdir -p $$HOME/.local/share/devhelp/Requests"117 @echo "# ln -s $(BUILDDIR)/devhelp $$HOME/.local/share/devhelp/Requests"118 @echo "# devhelp"119120.PHONY: epub121epub:122 $(SPHINXBUILD) -b epub $(ALLSPHINXOPTS) $(BUILDDIR)/epub123 @echo124 @echo "Build finished. The epub file is in $(BUILDDIR)/epub."125126.PHONY: latex127latex:128 $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex129 @echo130 @echo "Build finished; the LaTeX files are in $(BUILDDIR)/latex."131 @echo "Run \`make' in that directory to run these through (pdf)latex" \132 "(use \`make latexpdf' here to do that automatically)."133134.PHONY: latexpdf135latexpdf:136 $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex137 @echo "Running LaTeX files through pdflatex..."108 make -C $(BUILDDIR)/latex all-pdf138 $(MAKE) -C $(BUILDDIR)/latex all-pdf139 @echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex."140141.PHONY: latexpdfja142latexpdfja:143 $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex144 @echo "Running LaTeX files through platex and dvipdfmx..."145 $(MAKE) -C $(BUILDDIR)/latex all-pdf-ja146 @echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex."147148.PHONY: text149text:150 $(SPHINXBUILD) -b text $(ALLSPHINXOPTS) $(BUILDDIR)/text151 @echo152 @echo "Build finished. The text files are in $(BUILDDIR)/text."153154.PHONY: man155man:156 $(SPHINXBUILD) -b man $(ALLSPHINXOPTS) $(BUILDDIR)/man157 @echo158 @echo "Build finished. The manual pages are in $(BUILDDIR)/man."159160.PHONY: texinfo161texinfo:162 $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo163 @echo164 @echo "Build finished. The Texinfo files are in $(BUILDDIR)/texinfo."165 @echo "Run \`make' in that directory to run these through makeinfo" \166 "(use \`make info' here to do that automatically)."167168.PHONY: info169info:170 $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo171 @echo "Running Texinfo files through makeinfo..."172 make -C $(BUILDDIR)/texinfo info173 @echo "makeinfo finished; the Info files are in $(BUILDDIR)/texinfo."174175.PHONY: gettext176gettext:177 $(SPHINXBUILD) -b gettext $(I18NSPHINXOPTS) $(BUILDDIR)/locale178 @echo179 @echo "Build finished. The message catalogs are in $(BUILDDIR)/locale."180181.PHONY: changes182changes:183 $(SPHINXBUILD) -b changes $(ALLSPHINXOPTS) $(BUILDDIR)/changes184 @echo185 @echo "The overview file is in $(BUILDDIR)/changes."186187.PHONY: linkcheck188linkcheck:189 $(SPHINXBUILD) -b linkcheck $(ALLSPHINXOPTS) $(BUILDDIR)/linkcheck190 @echo191 @echo "Link check complete; look for any errors in the above output " \192 "or in $(BUILDDIR)/linkcheck/output.txt."193194.PHONY: doctest195doctest:196 $(SPHINXBUILD) -b doctest $(ALLSPHINXOPTS) $(BUILDDIR)/doctest197 @echo "Testing of doctests in the sources finished, look at the " \198 "results in $(BUILDDIR)/doctest/output.txt."199200.PHONY: coverage201coverage:202 $(SPHINXBUILD) -b coverage $(ALLSPHINXOPTS) $(BUILDDIR)/coverage203 @echo "Testing of coverage in the sources finished, look at the " \204 "results in $(BUILDDIR)/coverage/python.txt."205206.PHONY: xml207xml:208 $(SPHINXBUILD) -b xml $(ALLSPHINXOPTS) $(BUILDDIR)/xml209 @echo210 @echo "Build finished. The XML files are in $(BUILDDIR)/xml."211212.PHONY: pseudoxml213pseudoxml:214 $(SPHINXBUILD) -b pseudoxml $(ALLSPHINXOPTS) $(BUILDDIR)/pseudoxml215 @echo216 @echo "Build finished. The pseudo-XML files are in $(BUILDDIR)/pseudoxml."
deleted:docs/MANIFEST.in-1 removed
1include HISTORY.rst README.rst LICENSE
deleted:docs/requirements.txt-1 removed
1Sphinx==1.1.3
modified:requests/packages/urllib3/contrib/appengine.py+12 added-11 removed
1from __future__ import absolute_import2import logging3import os4import warnings5
54 unmodified lines
60 if not urlfetch:61 raise AppEnginePlatformError(62 "URLFetch is not available in this environment.")6363 if is_prod_appengine_v2():64 if is_prod_appengine_mvms():65 raise AppEnginePlatformError(66 "Use normal urllib3.PoolManager instead of AppEngineManager"67 "on Managed VMs, as using URLFetch is not necessary in "68 "this environment.")
39 unmodified lines
108 except urlfetch.DeadlineExceededError as e:109 raise TimeoutError(self, e)110111 except urlfetch.InvalidURLError as e:111 if 'too large' in e.message:112 if 'too large' in str(e):113 raise AppEnginePlatformError(114 "URLFetch request too large, URLFetch only "115 "supports requests up to 10mb in size.", e)116 raise ProtocolError(e)117118 except urlfetch.DownloadError as e:118 if 'Too many redirects' in e.message:119 if 'Too many redirects' in str(e):120 raise MaxRetryError(self, url, reason=e)121 raise ProtocolError(e)122123 except urlfetch.ResponseTooLargeError as e:
31 unmodified lines
155 return http_response156157 def _urlfetch_response_to_http_response(self, urlfetch_resp, **response_kw):158158 if is_prod_appengine_v1():159 if is_prod_appengine():160 # Production GAE handles deflate encoding automatically, but does161 # not remove the encoding header.162 content_encoding = urlfetch_resp.headers.get('content-encoding')163
12 unmodified lines
176 def _get_absolute_timeout(self, timeout):177 if timeout is Timeout.DEFAULT_TIMEOUT:178 return 5 # 5s is the default timeout for URLFetch.179 if isinstance(timeout, Timeout):179 if not timeout.read is timeout.connect:180 if timeout.read is not timeout.connect:181 warnings.warn(182 "URLFetch does not support granular timeout settings, "183 "reverting to total timeout.", AppEnginePlatformWarning)184 return timeout.total
14 unmodified lines
199200201def is_appengine():202 return (is_local_appengine() or202 is_prod_appengine_v1() or203 is_prod_appengine_v2())203 is_prod_appengine() or204 is_prod_appengine_mvms())205206207def is_appengine_sandbox():207 return is_appengine() and not is_prod_appengine_v2()208 return is_appengine() and not is_prod_appengine_mvms()209210211def is_local_appengine():212 return ('APPENGINE_RUNTIME' in os.environ and213 'Development/' in os.environ['SERVER_SOFTWARE'])214215215def is_prod_appengine_v1():216def is_prod_appengine():217 return ('APPENGINE_RUNTIME' in os.environ and218 'Google App Engine/' in os.environ['SERVER_SOFTWARE'] and218 not is_prod_appengine_v2())219 not is_prod_appengine_mvms())220221221def is_prod_appengine_v2():222def is_prod_appengine_mvms():223 return os.environ.get('GAE_VM', False) == 'true'
modified:requests/packages/urllib3/contrib/ntlmpool.py+1 added
1 unmodified line
2NTLM authenticating pool, contributed by erikcederstran34Issue #10, see: http://code.google.com/p/urllib3/issues/detail?id=105"""6from __future__ import absolute_import78try:9 from http.client import HTTPSConnection10except ImportError:
105 unmodified lines
modified:requests/packages/urllib3/contrib/pyopenssl.py+18 added-17 removed
41 unmodified lines
42.. _sni: https://en.wikipedia.org/wiki/Server_Name_Indication43.. _crime attack: https://en.wikipedia.org/wiki/CRIME_(security_exploit)4445'''46from __future__ import absolute_import4748try:49 from ndg.httpsclient.ssl_peer_verification import SUBJ_ALT_NAME_SUPPORT50 from ndg.httpsclient.subj_alt_name import SubjectAltName as BaseSubjectAltName
2 unmodified lines
5354import OpenSSL.SSL55from pyasn1.codec.der import decoder as der_decoder56from pyasn1.type import univ, constraint56from socket import _fileobject, timeout57from socket import _fileobject, timeout, error as SocketError58import ssl59import select6061from .. import connection
9 unmodified lines
71 ssl.PROTOCOL_SSLv23: OpenSSL.SSL.SSLv23_METHOD,72 ssl.PROTOCOL_TLSv1: OpenSSL.SSL.TLSv1_METHOD,73}7475if hasattr(ssl, 'PROTOCOL_TLSv1_1') and hasattr(OpenSSL.SSL, 'TLSv1_1_METHOD'):76 _openssl_versions[ssl.PROTOCOL_TLSv1_1] = OpenSSL.SSL.TLSv1_1_METHOD7778if hasattr(ssl, 'PROTOCOL_TLSv1_2') and hasattr(OpenSSL.SSL, 'TLSv1_2_METHOD'):79 _openssl_versions[ssl.PROTOCOL_TLSv1_2] = OpenSSL.SSL.TLSv1_2_METHOD8081try:82 _openssl_versions.update({ssl.PROTOCOL_SSLv3: OpenSSL.SSL.SSLv3_METHOD})83except AttributeError:84 pass8586_openssl_verify = {87 ssl.CERT_NONE: OpenSSL.SSL.VERIFY_NONE,88 ssl.CERT_OPTIONAL: OpenSSL.SSL.VERIFY_PEER,82 ssl.CERT_REQUIRED: OpenSSL.SSL.VERIFY_PEER83 + OpenSSL.SSL.VERIFY_FAIL_IF_NO_PEER_CERT,89 ssl.CERT_REQUIRED:90 OpenSSL.SSL.VERIFY_PEER + OpenSSL.SSL.VERIFY_FAIL_IF_NO_PEER_CERT,91}9293DEFAULT_SSL_CIPHER_LIST = util.ssl_.DEFAULT_CIPHERS9495# OpenSSL will only write 16K at a time96SSL_WRITE_BLOCKSIZE = 163849791try:92 _ = memoryview93 has_memoryview = True94except NameError:95 has_memoryview = False9698orig_util_HAS_SNI = util.HAS_SNI99orig_connection_ssl_wrap_socket = connection.ssl_wrap_socket100101
10 unmodified lines
112 connection.ssl_wrap_socket = orig_connection_ssl_wrap_socket113 util.HAS_SNI = orig_util_HAS_SNI114115115### Note: This is a slightly bug-fixed version of same from ndg-httpsclient.116# Note: This is a slightly bug-fixed version of same from ndg-httpsclient.117class SubjectAltName(BaseSubjectAltName):118 '''ASN.1 implementation for subjectAltNames support'''119120 # There is no limit to how many SAN certificates a certificate may have,
2 unmodified lines
123 sizeSpec = univ.SequenceOf.sizeSpec + \124 constraint.ValueSizeConstraint(1, 1024)125126126### Note: This is a slightly bug-fixed version of same from ndg-httpsclient.127# Note: This is a slightly bug-fixed version of same from ndg-httpsclient.128def get_subj_alt_name(peer_cert):129 # Search through extensions130 dns_name = []131 if not SUBJ_ALT_NAME_SUPPORT:
49 unmodified lines
181 except OpenSSL.SSL.SysCallError as e:182 if self.suppress_ragged_eofs and e.args == (-1, 'Unexpected EOF'):183 return b''184 else:184 raise185 raise SocketError(e)186 except OpenSSL.SSL.ZeroReturnError as e:187 if self.connection.get_shutdown() == OpenSSL.SSL.RECEIVED_SHUTDOWN:188 return b''189 else:
22 unmodified lines
212 raise timeout()213 continue214215 def sendall(self, data):215 if has_memoryview and not isinstance(data, memoryview):216 data = memoryview(data)217216 total_sent = 0217 while total_sent < len(data):220 sent = self._send_until_done(data[total_sent:total_sent+SSL_WRITE_BLOCKSIZE])218 sent = self._send_until_done(data[total_sent:total_sent + SSL_WRITE_BLOCKSIZE])219 total_sent += sent220221 def shutdown(self):222 # FIXME rethrow compatible exceptions should we ever use this223 self.connection.shutdown()224225 def close(self):226 if self._makefile_refs < 1:227 try:229 return self.connection.close()228 return self.connection.close()229 except OpenSSL.SSL.Error:230 return231 else:232 self._makefile_refs -= 1233234 def getpeercert(self, binary_form=False):
76 unmodified lines
added:requests/packages/urllib3/packages/ssl_match_hostname/.gitignore+1 added
1env
modified:requests/packages/urllib3/packages/__init__.py+1 added
1from __future__ import absolute_import23from . import ssl_match_hostname45__all__ = ('ssl_match_hostname', )
modified:requests/packages/urllib3/util/__init__.py+20 added
1from __future__ import absolute_import2# For backwards compatibility, provide imports that used to be here.3from .connection import is_connection_dropped4from .request import make_headers5from .response import is_fp_closed
16 unmodified lines
22 parse_url,23 split_first,24 Url,25)2627__all__ = (28 'HAS_SNI',29 'SSLContext',30 'Retry',31 'Timeout',32 'Url',33 'assert_fingerprint',34 'current_time',35 'is_connection_dropped',36 'is_fp_closed',37 'get_host',38 'parse_url',39 'make_headers',40 'resolve_cert_reqs',41 'resolve_ssl_version',42 'split_first',43 'ssl_wrap_socket',44)
modified:requests/packages/urllib3/util/connection.py+1 added
1from __future__ import absolute_import2import socket3try:4 from select import poll, POLLIN5except ImportError: # `poll` doesn't exist on OSX and other platforms
96 unmodified lines
modified:requests/packages/urllib3/util/request.py+1 added
1from __future__ import absolute_import2from base64 import b64encode34from ..packages.six import b5
67 unmodified lines
modified:requests/packages/urllib3/util/response.py+2 added-1 removed
1from __future__ import absolute_import2from ..packages.six.moves import http_client as httplib34from ..exceptions import HeaderParsingError5
38 unmodified lines
4445 # This will fail silently if we pass in the wrong kind of parameter.46 # To make debugging easier add an explicit check.47 if not isinstance(headers, httplib.HTTPMessage):47 raise TypeError('expected httplib.Message, got {}.'.format(48 raise TypeError('expected httplib.Message, got {0}.'.format(49 type(headers)))5051 defects = getattr(headers, 'defects', None)52 get_payload = getattr(headers, 'get_payload', None)
22 unmodified lines
modified:requests/packages/urllib3/util/retry.py+4 added-3 removed
1from __future__ import absolute_import2import time3import logging45from ..exceptions import (
120 unmodified lines
126 self.status_forcelist = status_forcelist or set()127 self.method_whitelist = method_whitelist128 self.backoff_factor = backoff_factor129 self.raise_on_redirect = raise_on_redirect129 self._observed_errors = _observed_errors # TODO: use .history instead?130 self._observed_errors = _observed_errors # TODO: use .history instead?131132 def new(self, **kw):133 params = dict(134 total=self.total,
71 unmodified lines
206 return False207208 return min(retry_counts) < 0209209 def increment(self, method=None, url=None, response=None, error=None, _pool=None, _stacktrace=None):210 def increment(self, method=None, url=None, response=None, error=None,211 _pool=None, _stacktrace=None):212 """ Return a new Retry object with incremented retry counters.213214 :param response: A response object, or None, if the server did not215 return a response.
59 unmodified lines
275 log.debug("Incremented Retry for (url='%s'): %r" % (url, new_retry))276277 return new_retry278277279 def __repr__(self):280 return ('{cls.__name__}(total={self.total}, connect={self.connect}, '281 'read={self.read}, redirect={self.redirect})').format(282 cls=type(self), self=self)
4 unmodified lines
modified:requests/packages/urllib3/util/ssl_.py+35 added-4 removed
1from __future__ import absolute_import2import errno3import warnings4import hmac56from binascii import hexlify, unhexlify7from hashlib import md5, sha1, sha25684from ..exceptions import SSLError, InsecurePlatformWarning9from ..exceptions import SSLError, InsecurePlatformWarning, SNIMissingWarning101112SSLContext = None13HAS_SNI = False
5 unmodified lines
19 40: sha1,20 64: sha256,21}2218import errno19import warnings2324def _const_compare_digest_backport(a, b):25 """26 Compare two digests of equal length in constant time.2728 The digests must be of type str/bytes.29 Returns True if the digests match, and False otherwise.30 """31 result = abs(len(a) - len(b))32 for l, r in zip(bytearray(a), bytearray(b)):33 result |= l ^ r34 return result == 0353637_const_compare_digest = getattr(hmac, 'compare_digest',38 _const_compare_digest_backport)394041try: # Test for SSL features42 import ssl43 from ssl import wrap_socket, CERT_NONE, PROTOCOL_SSLv2344 from ssl import HAS_SNI # Has SNI?
108 unmodified lines
153 fingerprint_bytes = unhexlify(fingerprint.encode())154155 cert_digest = hashfunc(cert).digest()156137 if cert_digest != fingerprint_bytes:157 if not _const_compare_digest(cert_digest, fingerprint_bytes):158 raise SSLError('Fingerprints did not match. Expected "{0}", got "{1}".'159 .format(fingerprint, hexlify(cert_digest)))160161
140 unmodified lines
302 if certfile:303 context.load_cert_chain(certfile, keyfile)304 if HAS_SNI: # Platform-specific: OpenSSL with enabled SNI305 return context.wrap_socket(sock, server_hostname=server_hostname)306307 warnings.warn(308 'An HTTPS request has been made, but the SNI (Subject Name '309 'Indication) extension to TLS is not available on this platform. '310 'This may cause the server to present an incorrect TLS '311 'certificate, which can cause validation failures. For more '312 'information, see '313 'https://urllib3.readthedocs.org/en/latest/security.html'314 '#snimissingwarning.',315 SNIMissingWarning316 )317 return context.wrap_socket(sock)
modified:requests/packages/urllib3/util/timeout.py+5 added-3 removed
1from __future__ import absolute_import2# The default socket timeout, used by httplib to indicate that no timeout was3# specified by the user4from socket import _GLOBAL_DEFAULT_TIMEOUT5import time
3 unmodified lines
9# A sentinel value to indicate that no timeout was specified by the user in10# urllib311_Default = object()121314def current_time():15 """16 Retrieve the current time. This function is mocked out in unit testing.17 """
209 unmodified lines
227 :raises urllib3.exceptions.TimeoutStateError: If :meth:`start_connect`228 has not yet been called on this object.229 """230 if (self.total is not None and229 self.total is not self.DEFAULT_TIMEOUT and230 self._read is not None and231 self._read is not self.DEFAULT_TIMEOUT):231 self.total is not self.DEFAULT_TIMEOUT and232 self._read is not None and233 self._read is not self.DEFAULT_TIMEOUT):234 # In case the connect timeout has not yet been established.235 if self._start_connect is None:236 return self._read237 return max(0, min(self.total - self.get_connect_duration(),
5 unmodified lines
modified:requests/packages/urllib3/util/url.py+4 added-1 removed
1from __future__ import absolute_import2from collections import namedtuple34from ..exceptions import LocationParseError5
79 unmodified lines
8586 def __str__(self):87 return self.url888990def split_first(s, delims):91 """92 Given a string and an iterable of delimiters, split on the first found93 delimiter. Return two split parts and the matched delimiter.
22 unmodified lines
116117 if min_idx is None or min_idx < 0:118 return s, '', None119118 return s[:min_idx], s[min_idx+1:], min_delim120 return s[:min_idx], s[min_idx + 1:], min_delim121122123def parse_url(url):124 """
82 unmodified lines
207 path, query = path.split('?', 1)208209 return Url(scheme, auth, host, port, path, query, fragment)210211212def get_host(url):213 """214 Deprecated. Use :func:`.parse_url` instead.215 """
2 unmodified lines
modified:requests/packages/urllib3/__init__.py+27 added-5 removed
1"""2urllib3 - Thread-safe connection pooling and re-using.3"""45__author__ = 'Andrey Petrov (andrey.petrov@shazow.net)'6__license__ = 'MIT'7__version__ = '1.12'5from __future__ import absolute_import6import warnings798from .connectionpool import (9 HTTPConnectionPool,10 HTTPSConnectionPool,11 connection_from_url
17 unmodified lines
29 class NullHandler(logging.Handler):30 def emit(self, record):31 pass3233__author__ = 'Andrey Petrov (andrey.petrov@shazow.net)'34__license__ = 'MIT'35__version__ = '1.13.1'3637__all__ = (38 'HTTPConnectionPool',39 'HTTPSConnectionPool',40 'PoolManager',41 'ProxyManager',42 'HTTPResponse',43 'Retry',44 'Timeout',45 'add_stderr_logger',46 'connection_from_url',47 'disable_warnings',48 'encode_multipart_formdata',49 'get_host',50 'make_headers',51 'proxy_from_url',52)5354logging.getLogger(__name__).addHandler(NullHandler())555657def add_stderr_logger(level=logging.DEBUG):58 """59 Helper for quickly adding a StreamHandler to the logger. Useful for60 debugging.
13 unmodified lines
74# ... Clean up.75del NullHandler767758import warnings78# SecurityWarning's always go off by default.79warnings.simplefilter('always', exceptions.SecurityWarning, append=True)80# SubjectAltNameWarning's should go off once per host81warnings.simplefilter('default', exceptions.SubjectAltNameWarning)82# InsecurePlatformWarning's don't vary between requests, so we keep it default.83warnings.simplefilter('default', exceptions.InsecurePlatformWarning,84 append=True)85# SNIMissingWarnings should go off only once.86warnings.simplefilter('default', exceptions.SNIMissingWarning)878889def disable_warnings(category=exceptions.HTTPWarning):90 """91 Helper for quickly disabling all urllib3 warnings.92 """
1 unmodified line
modified:requests/packages/urllib3/_collections.py+4 added-3 removed
1from __future__ import absolute_import2from collections import Mapping, MutableMapping3try:4 from threading import RLock5except ImportError: # Platform-specific: No threads available
161 unmodified lines
167168 def __ne__(self, other):169 return not self.__eq__(other)170170 if not PY3: # Python 2171 if not PY3: # Python 2172 iterkeys = MutableMapping.iterkeys173 itervalues = MutableMapping.itervalues174175 __marker = object()
58 unmodified lines
234 with self.add instead of self.__setitem__235 """236 if len(args) > 1:237 raise TypeError("extend() takes at most 1 positional "237 "arguments ({} given)".format(len(args)))238 "arguments ({0} given)".format(len(args)))239 other = args[0] if len(args) >= 1 else ()240241 if isinstance(other, HTTPHeaderDict):242 for key, val in other.iteritems():
61 unmodified lines
304 def items(self):305 return list(self.iteritems())306307 @classmethod307 def from_httplib(cls, message): # Python 2308 def from_httplib(cls, message): # Python 2309 """Read headers from a Python 2 httplib message object."""310 # python2.7 does not expose a proper API for exporting multiheaders311 # efficiently. This function re-reads raw lines from the message312 # object and extracts the multiheaders properly.
12 unmodified lines
modified:requests/packages/urllib3/connection.py+25 added-14 removed
1from __future__ import absolute_import2import datetime3import os4import sys5import socket6from socket import error as SocketError, timeout as SocketTimeout7import warnings8from .packages import six910try: # Python 39 from http.client import HTTPConnection as _HTTPConnection, HTTPException11 from http.client import HTTPConnection as _HTTPConnection12 from http.client import HTTPException # noqa: unused in this module13except ImportError:11 from httplib import HTTPConnection as _HTTPConnection, HTTPException14 from httplib import HTTPConnection as _HTTPConnection15 from httplib import HTTPException # noqa: unused in this module161314class DummyConnection(object):15 "Used to detect a failed ConnectionCls import."16 pass171817try: # Compiled with SSL?20 HTTPSConnection = DummyConnection18 import ssl19 BaseSSLError = ssl.SSLError20except (ImportError, AttributeError): # Platform-specific: No SSL.21 ssl = None
35 unmodified lines
5758RECENT_DATE = datetime.date(2014, 1, 1)596061class DummyConnection(object):62 """Used to detect a failed ConnectionCls import."""63 pass646566class HTTPConnection(_HTTPConnection, object):67 """68 Based on httplib.HTTPConnection but provides an extra constructor69 backwards-compatibility layer between older and newer Pythons.
136 unmodified lines
206207 self.key_file = key_file208 self.cert_file = cert_file209 self.cert_reqs = cert_reqs208 self.ca_certs = ca_certs209 self.ca_cert_dir = ca_cert_dir210 self.assert_hostname = assert_hostname211 self.assert_fingerprint = assert_fingerprint212 self.ca_certs = ca_certs and os.path.expanduser(ca_certs)213 self.ca_cert_dir = ca_cert_dir and os.path.expanduser(ca_cert_dir)214215 def connect(self):216 # Add certificate verification217 conn = self._new_conn()
46 unmodified lines
264 'deprecated by RFC 2818. (See https://github.com/shazow/urllib3/issues/497 '265 'for details.)'.format(hostname)),266 SubjectAltNameWarning267 )266 match_hostname(cert, self.assert_hostname or hostname)268268 self.is_verified = (resolved_cert_reqs == ssl.CERT_REQUIRED269 or self.assert_fingerprint is not None)269 # In case the hostname is an IPv6 address, strip the square270 # brackets from it before using it to validate. This is because271 # a certificate with an IPv6 address in it won't have square272 # brackets around that address. Sadly, match_hostname won't do this273 # for us: it expects the plain host part without any extra work274 # that might have been done to make it palatable to httplib.275 asserted_hostname = self.assert_hostname or hostname276 asserted_hostname = asserted_hostname.strip('[]')277 match_hostname(cert, asserted_hostname)278279 self.is_verified = (resolved_cert_reqs == ssl.CERT_REQUIRED or280 self.assert_fingerprint is not None)281282283if ssl:284 # Make a copy for testing.285 UnverifiedHTTPSConnection = HTTPSConnection286 HTTPSConnection = VerifiedHTTPSConnection
2 unmodified lines
modified:requests/packages/urllib3/connectionpool.py+18 added-16 removed
1from __future__ import absolute_import2import errno3import logging4import sys5import warnings
4 unmodified lines
10try: # Python 311 from queue import LifoQueue, Empty, Full12except ImportError:13 from Queue import LifoQueue, Empty, Full13 import Queue as _ # Platform-specific: Windows14 # Queue is imported for side effects on MS Windows15 import Queue as _unused_module_Queue # noqa: unused161718from .exceptions import (19 ClosedPoolError,
3 unmodified lines
23 HostChangedError,24 LocationValueError,25 MaxRetryError,26 ProxyError,25 ConnectTimeoutError,27 ReadTimeoutError,28 SSLError,29 TimeoutError,30 InsecureRequestWarning,
4 unmodified lines
35from .connection import (36 port_by_scheme,37 DummyConnection,38 HTTPConnection, HTTPSConnection, VerifiedHTTPSConnection,38 HTTPException, BaseSSLError, ConnectionError39 HTTPException, BaseSSLError,40)41from .request import RequestMethods42from .response import HTTPResponse43
10 unmodified lines
5455_Default = object()565757## Pool objects58# Pool objects59class ConnectionPool(object):60 """61 Base class for all connection pools, such as62 :class:`.HTTPConnectionPool` and :class:`.HTTPSConnectionPool`.
5 unmodified lines
68 def __init__(self, host, port=None):69 if not host:70 raise LocationValueError("No host specified.")7171 # httplib doesn't like it when we include brackets in ipv6 addresses72 self.host = host.strip('[]')72 self.host = host73 self.port = port7475 def __str__(self):76 return '%s(host=%r, port=%r)' % (type(self).__name__,
567 unmodified lines
644 raise645 return response646647 log.info("Redirecting %s -> %s" % (url, redirect_location))648 return self.urlopen(648 return self.urlopen(method, redirect_location, body, headers,649 retries=retries, redirect=redirect,650 assert_same_host=assert_same_host,651 timeout=timeout, pool_timeout=pool_timeout,652 release_conn=release_conn, **response_kw)649 method, redirect_location, body, headers,650 retries=retries, redirect=redirect,651 assert_same_host=assert_same_host,652 timeout=timeout, pool_timeout=pool_timeout,653 release_conn=release_conn, **response_kw)654655 # Check if we should retry the HTTP response.656 if retries.is_forced_retry(method, status_code=response.status):657 retries = retries.increment(method, url, response=response, _pool=self)658 retries.sleep()659 log.info("Forced retry: %s" % url)660 return self.urlopen(659 return self.urlopen(method, url, body, headers,660 retries=retries, redirect=redirect,661 assert_same_host=assert_same_host,662 timeout=timeout, pool_timeout=pool_timeout,663 release_conn=release_conn, **response_kw)661 method, url, body, headers,662 retries=retries, redirect=redirect,663 assert_same_host=assert_same_host,664 timeout=timeout, pool_timeout=pool_timeout,665 release_conn=release_conn, **response_kw)666667 return response668669
149 unmodified lines
modified:requests/packages/urllib3/exceptions.py+11 added-3 removed
1from __future__ import absolute_import2# Base Exceptions32## Base Exceptions45class HTTPError(Exception):6 "Base exception used by this module."7 pass8910class HTTPWarning(Warning):11 "Base warning used by this module."12 pass13141315class PoolError(HTTPError):16 "Base exception for errors caused within a pool."17 def __init__(self, pool, message):18 self.pool = pool
38 unmodified lines
57#: Renamed to ProtocolError but aliased for backwards compatibility.58ConnectionError = ProtocolError596060## Leaf Exceptions61# Leaf Exceptions6263class MaxRetryError(RequestError):64 """Raised when the maximum number of retries is exceeded.65
46 unmodified lines
112class ConnectTimeoutError(TimeoutError):113 "Raised when a socket timeout occurs while connecting to a server"114 pass115116117class NewConnectionError(ConnectTimeoutError, PoolError):118 "Raised when we fail to establish a new connection. Usually ECONNREFUSED."119 pass120121122class EmptyPoolError(PoolError):123 "Raised when a pool runs out of connections and no more are allowed."124 pass125
48 unmodified lines
174 "Warned when certain SSL configuration is not available on a platform."175 pass176177178class SNIMissingWarning(HTTPWarning):179 "Warned when making a HTTPS request without SNI available."180 pass181182183class ResponseNotChunked(ProtocolError, ValueError):184 "Response needs to be chunked in order to read it as chunks."185 pass186
15 unmodified lines
modified:requests/packages/urllib3/fields.py+1 added
1from __future__ import absolute_import2import email.utils3import mimetypes45from .packages import six
173 unmodified lines
modified:requests/packages/urllib3/filepost.py+1 added
1from __future__ import absolute_import2import codecs34from uuid import uuid45from io import BytesIO
89 unmodified lines
modified:requests/packages/urllib3/poolmanager.py+2 added-1 removed
1from __future__ import absolute_import2import logging34try: # Python 35 from urllib.parse import urljoin
19 unmodified lines
2526log = logging.getLogger(__name__)2728SSL_KEYWORDS = ('key_file', 'cert_file', 'cert_reqs', 'ca_certs',28 'ssl_version')29 'ssl_version', 'ca_cert_dir')303132class PoolManager(RequestMethods):33 """
248 unmodified lines
modified:requests/packages/urllib3/request.py+3 added-1 removed
1from __future__ import absolute_import2try:3 from urllib.parse import urlencode4except ImportError:5 from urllib import urlencode
127 unmodified lines
133 extra_kw = {'headers': {}}134135 if fields:136 if 'body' in urlopen_kw:136 raise TypeError('request got values for both \'fields\' and \'body\', can only specify one.')137 raise TypeError(138 "request got values for both 'fields' and 'body', can only specify one.")139140 if encode_multipart:141 body, content_type = encode_multipart_formdata(fields, boundary=multipart_boundary)142 else:
9 unmodified lines
modified:requests/packages/urllib3/response.py+41 added-12 removed
1from __future__ import absolute_import2from contextlib import contextmanager3import zlib4import io5from socket import timeout as SocketTimeout6from socket import error as SocketError78from ._collections import HTTPHeaderDict9from .exceptions import (10 ProtocolError, DecodeError, ReadTimeoutError, ResponseNotChunked
120 unmodified lines
131 encodings = (enc.strip() for enc in tr_enc.split(","))132 if "chunked" in encodings:133 self.chunked = True134133 # We certainly don't want to preload content when the response is chunked.134 if not self.chunked and preload_content and not self._body:135 # If requested, preload the body.136 if preload_content and not self._body:137 self._body = self.read(decode_content=decode_content)138139 def get_redirect_location(self):140 """
54 unmodified lines
195 raise DecodeError(196 "Received response with content-encoding: %s, but "197 "failed to decode it." % content_encoding, e)198197 if flush_decoder and decode_content and self._decoder:198 buf = self._decoder.decompress(binary_type())199 data += buf + self._decoder.flush()199 if flush_decoder and decode_content:200 data += self._flush_decoder()201202 return data203204 def _flush_decoder(self):205 """206 Flushes the decoder. Should only be called if the decoder is actually207 being used.208 """209 if self._decoder:210 buf = self._decoder.decompress(b'')211 return buf + self._decoder.flush()212213 return b''214215 @contextmanager216 def _error_catcher(self):217 """218 Catch low-level python exceptions, instead re-raising urllib3
19 unmodified lines
238 raise239240 raise ReadTimeoutError(self._pool, None, 'Read timed out.')241230 except HTTPException as e:242 except (HTTPException, SocketError) as e:243 # This includes IncompleteRead.244 raise ProtocolError('Connection broken: %r' % e, e)245246 except Exception:247 # The response may not be closed but we're not going to use it anymore248 # so close it now to ensure that the connection is released back to the pool.249 if self._original_response and not self._original_response.isclosed():250 self._original_response.close()251252 # Closing the response may not actually be sufficient to close253 # everything, so if we have a hold of the connection close that254 # too.255 if self._connection is not None:256 self._connection.close()257258 raise259 finally:260 if self._original_response and self._original_response.isclosed():261 self.release_conn()
57 unmodified lines
319 self._body = data320321 return data322304323 def stream(self, amt=2**16, decode_content=None):324 """325 A generator wrapper for the read() method. A call will block until326 ``amt`` bytes have been read from the connection or until the
30 unmodified lines
357 """358 headers = r.msg359360 if not isinstance(headers, HTTPHeaderDict):343 if PY3: # Python 3361 if PY3: # Python 3362 headers = HTTPHeaderDict(headers.items())345 else: # Python 2363 else: # Python 2364 headers = HTTPHeaderDict.from_httplib(headers)365366 # HTTPResponse objects in Python 3 don't have a .strict attribute367 strict = getattr(r, 'strict', 0)
103 unmodified lines
471 """472 self._init_decoder()473 # FIXME: Rewrite this method and make it a class with a better structured logic.474 if not self.chunked:457 raise ResponseNotChunked("Response is not chunked. "475 raise ResponseNotChunked(476 "Response is not chunked. "477 "Header 'transfer-encoding: chunked' is missing.")478479 # Don't bother reading the body of a HEAD request.480 if self._original_response and is_response_to_head(self._original_response):
5 unmodified lines
486 self._update_chunk_length()487 if self.chunk_left == 0:488 break489 chunk = self._handle_chunk(amt)471 yield self._decode(chunk, decode_content=decode_content,472 flush_decoder=True)490 decoded = self._decode(chunk, decode_content=decode_content,491 flush_decoder=False)492 if decoded:493 yield decoded494495 if decode_content:496 # On CPython and PyPy, we should never need to flush the497 # decoder. However, on Jython we *might* need to, so498 # lets defensively do it anyway.499 decoded = self._flush_decoder()500 if decoded: # Platform-specific: Jython.501 yield decoded502503 # Chunk content ends with \r\n: discard it.504 while True:505 line = self._fp.fp.readline()506 if not line:
8 unmodified lines
modified:requests/__init__.py+3 added-3 removed
40 unmodified lines
4142"""4344__title__ = 'requests'45__version__ = '2.8.1'46__build__ = 0x02080145__version__ = '2.9.1'46__build__ = 0x02090147__author__ = 'Kenneth Reitz'48__license__ = 'Apache 2.0'49__copyright__ = 'Copyright 2015 Kenneth Reitz'49__copyright__ = 'Copyright 2016 Kenneth Reitz'5051# Attempt to enable urllib3's SNI support, if possible52try:53 from .packages.urllib3.contrib import pyopenssl
30 unmodified lines
modified:requests/adapters.py+2 added-2 removed
63 unmodified lines
64 covers.6566 :param pool_connections: The number of urllib3 connection pools to cache.67 :param pool_maxsize: The maximum number of connections to save in the pool.68 :param int max_retries: The maximum number of retries each connection68 :param max_retries: The maximum number of retries each connection69 should attempt. Note, this applies only to failed DNS lookups, socket70 connections and connection timeouts, never to requests where data has71 made it to the server. By default, Requests does not retry failed72 connections. If you need granular control over the conditions under
34 unmodified lines
107 self.__attrs__)108109 def __setstate__(self, state):110 # Can't handle by adding 'proxy_manager' to self.__attrs__ because111 # because self.poolmanager uses a lambda function, which isn't pickleable.111 # self.poolmanager uses a lambda function, which isn't pickleable.112 self.proxy_manager = {}113 self.config = {}114115 for attr, value in state.items():
338 unmodified lines
modified:requests/api.py+1 added-1 removed
31 unmodified lines
32 :type timeout: float or tuple33 :param allow_redirects: (optional) Boolean. Set to True if POST/PUT/DELETE redirect following is allowed.34 :type allow_redirects: bool35 :param proxies: (optional) Dictionary mapping protocol to the URL of the proxy.36 :param verify: (optional) if ``True``, the SSL cert will be verified. A CA_BUNDLE path can also be provided.36 :param verify: (optional) whether the SSL cert will be verified. A CA_BUNDLE path can also be provided. Defaults to ``True``.37 :param stream: (optional) if ``False``, the response content will be immediately downloaded.38 :param cert: (optional) if String, path to ssl client cert file (.pem). If Tuple, ('cert', 'key') pair.39 :return: :class:`Response <Response>` object40 :rtype: requests.Response
105 unmodified lines
modified:requests/auth.py+19 added-1 removed
45 unmodified lines
46 def __init__(self, username, password):47 self.username = username48 self.password = password4950 def __eq__(self, other):51 return all([52 self.username == getattr(other, 'username', None),53 self.password == getattr(other, 'password', None)54 ])5556 def __ne__(self, other):57 return not self == other5859 def __call__(self, r):60 r.headers['Authorization'] = _basic_auth_str(self.username, self.password)61 return r62
81 unmodified lines
144 cnonce = (hashlib.sha1(s).hexdigest()[:16])145 if _algorithm == 'MD5-SESS':146 HA1 = hash_utf8('%s:%s:%s' % (HA1, nonce, cnonce))147139 if qop is None:148 if not qop:149 respdig = KD(HA1, "%s:%s" % (nonce, HA2))150 elif qop == 'auth' or 'auth' in qop.split(','):151 noncebit = "%s:%s:%s:%s:%s" % (152 nonce, ncvalue, cnonce, 'auth', HA2
76 unmodified lines
229 r.register_hook('response', self.handle_redirect)230 self._thread_local.num_401_calls = 1231232 return r233234 def __eq__(self, other):235 return all([236 self.username == getattr(other, 'username', None),237 self.password == getattr(other, 'password', None)238 ])239240 def __ne__(self, other):241 return not self == other
modified:requests/cookies.py+5 added-3 removed
6 unmodified lines
7"""89import copy10import time11import calendar12import collections13from .compat import cookielib, urlparse, urlunparse, Morsel1415try:
352 unmodified lines
368 if jar is None:369 return None370371 if hasattr(jar, 'copy'):371 # We're dealing with an instane of RequestsCookieJar372 # We're dealing with an instance of RequestsCookieJar373 return jar.copy()374 # We're dealing with a generic CookieJar instance375 new_jar = copy.copy(jar)376 new_jar.clear()
47 unmodified lines
424 except ValueError:425 raise TypeError('max-age: %s must be integer' % morsel['max-age'])426 elif morsel['expires']:427 time_template = '%a, %d-%b-%Y %H:%M:%S GMT'427 expires = int(time.mktime(428 time.strptime(morsel['expires'], time_template)) - time.timezone)428 expires = calendar.timegm(429 time.strptime(morsel['expires'], time_template)430 )431 return create_cookie(432 comment=morsel['comment'],433 comment_url=bool(morsel['comment']),434 discard=False,
53 unmodified lines
modified:requests/models.py+7 added-4 removed
79 unmodified lines
80 if parameters are supplied as a dict.81 """8283 if isinstance(data, (str, bytes)):84 return to_native_string(data)84 return data85 elif hasattr(data, 'read'):86 return data87 elif hasattr(data, '__iter__'):88 result = []
234 unmodified lines
323324 def prepare_url(self, url, params):325 """Prepares the given HTTP URL."""326 #: Accept objects that have string representations.327 #: We're unable to blindy call unicode/str functions327 #: We're unable to blindly call unicode/str functions328 #: as this will include the bytestring indicator (b'')329 #: on python 3.x.330 #: https://github.com/kennethreitz/requests/pull/2238331 if isinstance(url, bytes):
52 unmodified lines
384 query = query.encode('utf-8')385 if isinstance(fragment, str):386 fragment = fragment.encode('utf-8')387388 if isinstance(params, (str, bytes)):389 params = to_native_string(params)390391 enc_params = self._encode_params(params)392 if enc_params:393 if query:394 query = '%s&%s' % (query, enc_params)
41 unmodified lines
436437 if files:438 raise NotImplementedError('Streamed bodies and files are mutually exclusive.')439437 if length is not None:440 if length:441 self.headers['Content-Length'] = builtin_str(length)442 else:443 self.headers['Transfer-Encoding'] = 'chunked'444 else:
188 unmodified lines
633 return ('location' in self.headers and self.status_code in REDIRECT_STATI)634635 @property636 def is_permanent_redirect(self):634 """True if this Response one of the permanant versions of redirect"""637 """True if this Response one of the permanent versions of redirect"""638 return ('location' in self.headers and self.status_code in (codes.moved_permanently, codes.permanent_redirect))639640 @property641 def apparent_encoding(self):
210 unmodified lines
modified:requests/sessions.py+15 added-13 removed
108 unmodified lines
109 except (ChunkedEncodingError, ContentDecodingError, RuntimeError):110 resp.raw.read(decode_content=False)111112 if i >= self.max_redirects:113 raise TooManyRedirects('Exceeded %s redirects.' % self.max_redirects)113 raise TooManyRedirects('Exceeded %s redirects.' % self.max_redirects, response=resp)114115 # Release the connection back into the pool.116 resp.close()117
206 unmodified lines
324 #: Maximum number of redirects allowed. If the request exceeds this325 #: limit, a :class:`TooManyRedirects` exception is raised.326 self.max_redirects = DEFAULT_REDIRECT_LIMIT327328 #: Trust environement settings for proxy configuration, default328 #: Trust environment settings for proxy configuration, default329 #: authentication and similar.330 self.trust_env = True331332 #: A CookieJar containing all currently outstanding cookies set on this
99 unmodified lines
432 :param proxies: (optional) Dictionary mapping protocol or protocol and433 hostname to the URL of the proxy.434 :param stream: (optional) whether to immediately download the response435 content. Defaults to ``False``.436 :param verify: (optional) if ``True``, the SSL cert will be verified.437 A CA_BUNDLE path can also be provided.436 :param verify: (optional) whether the SSL cert will be verified.437 A CA_BUNDLE path can also be provided. Defaults to ``True``.438 :param cert: (optional) if String, path to ssl client cert file (.pem).439 If Tuple, ('cert', 'key') pair.440 """441 # Create the Request.
110 unmodified lines
552 # Guard against that specific failure case.553 if not isinstance(request, PreparedRequest):554 raise ValueError('You can only send PreparedRequests.')555556 checked_urls = set()557 while request.url in self.redirect_cache:558 checked_urls.add(request.url)559 new_url = self.redirect_cache.get(request.url)560 if new_url in checked_urls:561 break562 request.url = new_url563556 # Set up variables needed for resolve_redirects and dispatching of hooks557 allow_redirects = kwargs.pop('allow_redirects', True)558 stream = kwargs.get('stream')559 hooks = request.hooks560561 # Resolve URL in redirect cache, if available.562 if allow_redirects:563 checked_urls = set()564 while request.url in self.redirect_cache:565 checked_urls.add(request.url)566 new_url = self.redirect_cache.get(request.url)567 if new_url in checked_urls:568 break569 request.url = new_url570571 # Get the appropriate adapter to use572 adapter = self.get_adapter(url=request.url)573574 # Start time (approximately) of the request
60 unmodified lines
635 return {'verify': verify, 'proxies': proxies, 'stream': stream,636 'cert': cert}637638 def get_adapter(self, url):637 """Returns the appropriate connnection adapter for the given URL."""639 """Returns the appropriate connection adapter for the given URL."""640 for (prefix, adapter) in self.adapters.items():641642 if url.lower().startswith(prefix):643 return adapter
39 unmodified lines
modified:requests/utils.py+6 added-2 removed
113 unmodified lines
114 return115116 ri = urlparse(url)117118 # Strip port numbers from netloc119 host = ri.netloc.split(':')[0]118 # Strip port numbers from netloc. This weird `if...encode`` dance is119 # used for Python 3.2, which doesn't support unicode literals.120 splitstr = b':'121 if isinstance(url, str):122 splitstr = splitstr.decode('ascii')123 host = ri.netloc.split(splitstr)[0]124125 try:126 _netrc = netrc(netrc_path).authenticators(host)127 if _netrc:
594 unmodified lines
added:tests/__init__.py+1 added
1# coding: utf-8
added:tests/compat.py+20 added
1# coding: utf-82from requests.compat import is_py3345try:6 import StringIO7except ImportError:8 import io as StringIO910try:11 from cStringIO import StringIO as cStringIO12except ImportError:13 cStringIO = None1415if is_py3:16 def u(s):17 return s18else:19 def u(s):20 return s.decode('unicode-escape')
added:tests/conftest.py+23 added
1# coding: utf-82import pytest3from requests.compat import urljoin456def prepare_url(value):7 # Issue #1483: Make sure the URL always has a trailing slash8 httpbin_url = value.url.rstrip('/') + '/'910 def inner(*suffix):11 return urljoin(httpbin_url, '/'.join(suffix))1213 return inner141516@pytest.fixture17def httpbin(httpbin):18 return prepare_url(httpbin)192021@pytest.fixture22def httpbin_secure(httpbin_secure):23 return prepare_url(httpbin_secure)
added:tests/test_requests.py+1458 added
1#!/usr/bin/env python2# -*- coding: utf-8 -*-34"""Tests for Requests."""56from __future__ import division7import json8import os9import pickle10import collections11import contextlib1213import io14import requests15import pytest16from requests.adapters import HTTPAdapter17from requests.auth import HTTPDigestAuth, _basic_auth_str18from requests.compat import (19 Morsel, cookielib, getproxies, str, urlparse,20 builtin_str, OrderedDict)21from requests.cookies import cookiejar_from_dict, morsel_to_cookie22from requests.exceptions import (23 ConnectionError, ConnectTimeout, InvalidSchema, InvalidURL,24 MissingSchema, ReadTimeout, Timeout, RetryError, TooManyRedirects)25from requests.models import PreparedRequest26from requests.structures import CaseInsensitiveDict27from requests.sessions import SessionRedirectMixin28from requests.models import urlencode29from requests.hooks import default_hooks30from .compat import StringIO, u3132# Requests to this URL should always fail with a connection timeout (nothing33# listening on that port)34TARPIT = 'http://10.255.255.1'353637class TestRequests:3839 def test_entry_points(self):4041 requests.session42 requests.session().get43 requests.session().head44 requests.get45 requests.head46 requests.put47 requests.patch48 requests.post4950 @pytest.mark.parametrize(51 'exception, url', (52 (MissingSchema, 'hiwpefhipowhefopw'),53 (InvalidSchema, 'localhost:3128'),54 (InvalidSchema, 'localhost.localdomain:3128/'),55 (InvalidSchema, '10.122.1.1:3128/'),56 (InvalidURL, 'http://'),57 ))58 def test_invalid_url(self, exception, url):59 with pytest.raises(exception):60 requests.get(url)6162 def test_basic_building(self):63 req = requests.Request()64 req.url = 'http://kennethreitz.org/'65 req.data = {'life': '42'}6667 pr = req.prepare()68 assert pr.url == req.url69 assert pr.body == 'life=42'7071 @pytest.mark.parametrize('method', ('GET', 'HEAD'))72 def test_no_content_length(self, httpbin, method):73 req = requests.Request(method, httpbin(method.lower())).prepare()74 assert 'Content-Length' not in req.headers7576 def test_override_content_length(self, httpbin):77 headers = {78 'Content-Length': 'not zero'79 }80 r = requests.Request('POST', httpbin('post'), headers=headers).prepare()81 assert 'Content-Length' in r.headers82 assert r.headers['Content-Length'] == 'not zero'8384 def test_path_is_not_double_encoded(self):85 request = requests.Request('GET', "http://0.0.0.0/get/test case").prepare()8687 assert request.path_url == '/get/test%20case'8889 @pytest.mark.parametrize(90 'url, expected', (91 ('http://example.com/path#fragment', 'http://example.com/path?a=b#fragment'),92 ('http://example.com/path?key=value#fragment', 'http://example.com/path?key=value&a=b#fragment')93 ))94 def test_params_are_added_before_fragment(self, url, expected):95 request = requests.Request('GET', url, params={"a": "b"}).prepare()96 assert request.url == expected9798 def test_params_original_order_is_preserved_by_default(self):99 param_ordered_dict = OrderedDict((('z', 1), ('a', 1), ('k', 1), ('d', 1)))100 session = requests.Session()101 request = requests.Request('GET', 'http://example.com/', params=param_ordered_dict)102 prep = session.prepare_request(request)103 assert prep.url == 'http://example.com/?z=1&a=1&k=1&d=1'104105 def test_params_bytes_are_encoded(self):106 request = requests.Request('GET', 'http://example.com',107 params=b'test=foo').prepare()108 assert request.url == 'http://example.com/?test=foo'109110 def test_binary_put(self):111 request = requests.Request('PUT', 'http://example.com',112 data=u"ööö".encode("utf-8")).prepare()113 assert isinstance(request.body, bytes)114115 @pytest.mark.parametrize('scheme', ('http://', 'HTTP://', 'hTTp://', 'HttP://'))116 def test_mixed_case_scheme_acceptable(self, httpbin, scheme):117 s = requests.Session()118 s.proxies = getproxies()119 parts = urlparse(httpbin('get'))120 url = scheme + parts.netloc + parts.path121 r = requests.Request('GET', url)122 r = s.send(r.prepare())123 assert r.status_code == 200, 'failed for scheme {0}'.format(scheme)124125 def test_HTTP_200_OK_GET_ALTERNATIVE(self, httpbin):126 r = requests.Request('GET', httpbin('get'))127 s = requests.Session()128 s.proxies = getproxies()129130 r = s.send(r.prepare())131132 assert r.status_code == 200133134 def test_HTTP_302_ALLOW_REDIRECT_GET(self, httpbin):135 r = requests.get(httpbin('redirect', '1'))136 assert r.status_code == 200137 assert r.history[0].status_code == 302138 assert r.history[0].is_redirect139140 def test_HTTP_302_TOO_MANY_REDIRECTS(self, httpbin):141 try:142 requests.get(httpbin('relative-redirect', '50'))143 except TooManyRedirects as e:144 url = httpbin('relative-redirect', '20')145 assert e.request.url == url146 assert e.response.url == url147 assert len(e.response.history) == 30148 else:149 pytest.fail('Expected redirect to raise TooManyRedirects but it did not')150151 def test_HTTP_302_TOO_MANY_REDIRECTS_WITH_PARAMS(self, httpbin):152 s = requests.session()153 s.max_redirects = 5154 try:155 s.get(httpbin('relative-redirect', '50'))156 except TooManyRedirects as e:157 url = httpbin('relative-redirect', '45')158 assert e.request.url == url159 assert e.response.url == url160 assert len(e.response.history) == 5161 else:162 pytest.fail('Expected custom max number of redirects to be respected but was not')163164 # def test_HTTP_302_ALLOW_REDIRECT_POST(self):165 # r = requests.post(httpbin('status', '302'), data={'some': 'data'})166 # self.assertEqual(r.status_code, 200)167168 def test_HTTP_200_OK_GET_WITH_PARAMS(self, httpbin):169 heads = {'User-agent': 'Mozilla/5.0'}170171 r = requests.get(httpbin('user-agent'), headers=heads)172173 assert heads['User-agent'] in r.text174 assert r.status_code == 200175176 def test_HTTP_200_OK_GET_WITH_MIXED_PARAMS(self, httpbin):177 heads = {'User-agent': 'Mozilla/5.0'}178179 r = requests.get(httpbin('get') + '?test=true', params={'q': 'test'}, headers=heads)180 assert r.status_code == 200181182 def test_set_cookie_on_301(self, httpbin):183 s = requests.session()184 url = httpbin('cookies/set?foo=bar')185 s.get(url)186 assert s.cookies['foo'] == 'bar'187188 def test_cookie_sent_on_redirect(self, httpbin):189 s = requests.session()190 s.get(httpbin('cookies/set?foo=bar'))191 r = s.get(httpbin('redirect/1')) # redirects to httpbin('get')192 assert 'Cookie' in r.json()['headers']193194 def test_cookie_removed_on_expire(self, httpbin):195 s = requests.session()196 s.get(httpbin('cookies/set?foo=bar'))197 assert s.cookies['foo'] == 'bar'198 s.get(199 httpbin('response-headers'),200 params={201 'Set-Cookie':202 'foo=deleted; expires=Thu, 01-Jan-1970 00:00:01 GMT'203 }204 )205 assert 'foo' not in s.cookies206207 def test_cookie_quote_wrapped(self, httpbin):208 s = requests.session()209 s.get(httpbin('cookies/set?foo="bar:baz"'))210 assert s.cookies['foo'] == '"bar:baz"'211212 def test_cookie_persists_via_api(self, httpbin):213 s = requests.session()214 r = s.get(httpbin('redirect/1'), cookies={'foo': 'bar'})215 assert 'foo' in r.request.headers['Cookie']216 assert 'foo' in r.history[0].request.headers['Cookie']217218 def test_request_cookie_overrides_session_cookie(self, httpbin):219 s = requests.session()220 s.cookies['foo'] = 'bar'221 r = s.get(httpbin('cookies'), cookies={'foo': 'baz'})222 assert r.json()['cookies']['foo'] == 'baz'223 # Session cookie should not be modified224 assert s.cookies['foo'] == 'bar'225226 def test_request_cookies_not_persisted(self, httpbin):227 s = requests.session()228 s.get(httpbin('cookies'), cookies={'foo': 'baz'})229 # Sending a request with cookies should not add cookies to the session230 assert not s.cookies231232 def test_generic_cookiejar_works(self, httpbin):233 cj = cookielib.CookieJar()234 cookiejar_from_dict({'foo': 'bar'}, cj)235 s = requests.session()236 s.cookies = cj237 r = s.get(httpbin('cookies'))238 # Make sure the cookie was sent239 assert r.json()['cookies']['foo'] == 'bar'240 # Make sure the session cj is still the custom one241 assert s.cookies is cj242243 def test_param_cookiejar_works(self, httpbin):244 cj = cookielib.CookieJar()245 cookiejar_from_dict({'foo': 'bar'}, cj)246 s = requests.session()247 r = s.get(httpbin('cookies'), cookies=cj)248 # Make sure the cookie was sent249 assert r.json()['cookies']['foo'] == 'bar'250251 def test_requests_in_history_are_not_overridden(self, httpbin):252 resp = requests.get(httpbin('redirect/3'))253 urls = [r.url for r in resp.history]254 req_urls = [r.request.url for r in resp.history]255 assert urls == req_urls256257 def test_history_is_always_a_list(self, httpbin):258 """Show that even with redirects, Response.history is always a list."""259 resp = requests.get(httpbin('get'))260 assert isinstance(resp.history, list)261 resp = requests.get(httpbin('redirect/1'))262 assert isinstance(resp.history, list)263 assert not isinstance(resp.history, tuple)264265 def test_headers_on_session_with_None_are_not_sent(self, httpbin):266 """Do not send headers in Session.headers with None values."""267 ses = requests.Session()268 ses.headers['Accept-Encoding'] = None269 req = requests.Request('GET', httpbin('get'))270 prep = ses.prepare_request(req)271 assert 'Accept-Encoding' not in prep.headers272273 @pytest.mark.parametrize('key', ('User-agent', 'user-agent'))274 def test_user_agent_transfers(self, httpbin, key):275276 heads = {key: 'Mozilla/5.0 (github.com/kennethreitz/requests)'}277278 r = requests.get(httpbin('user-agent'), headers=heads)279 assert heads[key] in r.text280281 def test_HTTP_200_OK_HEAD(self, httpbin):282 r = requests.head(httpbin('get'))283 assert r.status_code == 200284285 def test_HTTP_200_OK_PUT(self, httpbin):286 r = requests.put(httpbin('put'))287 assert r.status_code == 200288289 def test_BASICAUTH_TUPLE_HTTP_200_OK_GET(self, httpbin):290 auth = ('user', 'pass')291 url = httpbin('basic-auth', 'user', 'pass')292293 r = requests.get(url, auth=auth)294 assert r.status_code == 200295296 r = requests.get(url)297 assert r.status_code == 401298299 s = requests.session()300 s.auth = auth301 r = s.get(url)302 assert r.status_code == 200303304 @pytest.mark.parametrize(305 'url, exception', (306 # Connecting to an unknown domain should raise a ConnectionError307 ('http://doesnotexist.google.com', ConnectionError),308 # Connecting to an invalid port should raise a ConnectionError309 ('http://localhost:1', ConnectionError),310 # Inputing a URL that cannot be parsed should raise an InvalidURL error311 ('http://fe80::5054:ff:fe5a:fc0', InvalidURL)312 ))313 def test_errors(self, url, exception):314 with pytest.raises(exception):315 requests.get(url, timeout=1)316317 def test_basicauth_with_netrc(self, httpbin):318 auth = ('user', 'pass')319 wrong_auth = ('wronguser', 'wrongpass')320 url = httpbin('basic-auth', 'user', 'pass')321322 old_auth = requests.sessions.get_netrc_auth323324 try:325 def get_netrc_auth_mock(url):326 return auth327 requests.sessions.get_netrc_auth = get_netrc_auth_mock328329 # Should use netrc and work.330 r = requests.get(url)331 assert r.status_code == 200332333 # Given auth should override and fail.334 r = requests.get(url, auth=wrong_auth)335 assert r.status_code == 401336337 s = requests.session()338339 # Should use netrc and work.340 r = s.get(url)341 assert r.status_code == 200342343 # Given auth should override and fail.344 s.auth = wrong_auth345 r = s.get(url)346 assert r.status_code == 401347 finally:348 requests.sessions.get_netrc_auth = old_auth349350 def test_DIGEST_HTTP_200_OK_GET(self, httpbin):351352 auth = HTTPDigestAuth('user', 'pass')353 url = httpbin('digest-auth', 'auth', 'user', 'pass')354355 r = requests.get(url, auth=auth)356 assert r.status_code == 200357358 r = requests.get(url)359 assert r.status_code == 401360361 s = requests.session()362 s.auth = HTTPDigestAuth('user', 'pass')363 r = s.get(url)364 assert r.status_code == 200365366 def test_DIGEST_AUTH_RETURNS_COOKIE(self, httpbin):367 url = httpbin('digest-auth', 'auth', 'user', 'pass')368 auth = HTTPDigestAuth('user', 'pass')369 r = requests.get(url)370 assert r.cookies['fake'] == 'fake_value'371372 r = requests.get(url, auth=auth)373 assert r.status_code == 200374375 def test_DIGEST_AUTH_SETS_SESSION_COOKIES(self, httpbin):376 url = httpbin('digest-auth', 'auth', 'user', 'pass')377 auth = HTTPDigestAuth('user', 'pass')378 s = requests.Session()379 s.get(url, auth=auth)380 assert s.cookies['fake'] == 'fake_value'381382 def test_DIGEST_STREAM(self, httpbin):383384 auth = HTTPDigestAuth('user', 'pass')385 url = httpbin('digest-auth', 'auth', 'user', 'pass')386387 r = requests.get(url, auth=auth, stream=True)388 assert r.raw.read() != b''389390 r = requests.get(url, auth=auth, stream=False)391 assert r.raw.read() == b''392393 def test_DIGESTAUTH_WRONG_HTTP_401_GET(self, httpbin):394395 auth = HTTPDigestAuth('user', 'wrongpass')396 url = httpbin('digest-auth', 'auth', 'user', 'pass')397398 r = requests.get(url, auth=auth)399 assert r.status_code == 401400401 r = requests.get(url)402 assert r.status_code == 401403404 s = requests.session()405 s.auth = auth406 r = s.get(url)407 assert r.status_code == 401408409 def test_DIGESTAUTH_QUOTES_QOP_VALUE(self, httpbin):410411 auth = HTTPDigestAuth('user', 'pass')412 url = httpbin('digest-auth', 'auth', 'user', 'pass')413414 r = requests.get(url, auth=auth)415 assert '"auth"' in r.request.headers['Authorization']416417 def test_POSTBIN_GET_POST_FILES(self, httpbin):418419 url = httpbin('post')420 requests.post(url).raise_for_status()421422 post1 = requests.post(url, data={'some': 'data'})423 assert post1.status_code == 200424425 with open('requirements.txt') as f:426 post2 = requests.post(url, files={'some': f})427 assert post2.status_code == 200428429 post4 = requests.post(url, data='[{"some": "json"}]')430 assert post4.status_code == 200431432 with pytest.raises(ValueError):433 requests.post(url, files=['bad file data'])434435 def test_POSTBIN_GET_POST_FILES_WITH_DATA(self, httpbin):436437 url = httpbin('post')438 requests.post(url).raise_for_status()439440 post1 = requests.post(url, data={'some': 'data'})441 assert post1.status_code == 200442443 with open('requirements.txt') as f:444 post2 = requests.post(url,445 data={'some': 'data'}, files={'some': f})446 assert post2.status_code == 200447448 post4 = requests.post(url, data='[{"some": "json"}]')449 assert post4.status_code == 200450451 with pytest.raises(ValueError):452 requests.post(url, files=['bad file data'])453454 def test_conflicting_post_params(self, httpbin):455 url = httpbin('post')456 with open('requirements.txt') as f:457 pytest.raises(ValueError, "requests.post(url, data='[{\"some\": \"data\"}]', files={'some': f})")458 pytest.raises(ValueError, "requests.post(url, data=u('[{\"some\": \"data\"}]'), files={'some': f})")459460 def test_request_ok_set(self, httpbin):461 r = requests.get(httpbin('status', '404'))462 assert not r.ok463464 def test_status_raising(self, httpbin):465 r = requests.get(httpbin('status', '404'))466 with pytest.raises(requests.exceptions.HTTPError):467 r.raise_for_status()468469 r = requests.get(httpbin('status', '500'))470 assert not r.ok471472 def test_decompress_gzip(self, httpbin):473 r = requests.get(httpbin('gzip'))474 r.content.decode('ascii')475476 @pytest.mark.parametrize(477 'url, params', (478 ('/get', {'foo': 'føø'}),479 ('/get', {'føø': 'føø'}),480 ('/get', {'føø': 'føø'}),481 ('/get', {'foo': 'foo'}),482 ('ø', {'foo': 'foo'}),483 ))484 def test_unicode_get(self, httpbin, url, params):485 requests.get(httpbin(url), params=params)486487 def test_unicode_header_name(self, httpbin):488 requests.put(489 httpbin('put'),490 headers={str('Content-Type'): 'application/octet-stream'},491 data='\xff') # compat.str is unicode.492493 def test_pyopenssl_redirect(self, httpbin_secure, httpbin_ca_bundle):494 requests.get(httpbin_secure('status', '301'), verify=httpbin_ca_bundle)495496 def test_urlencoded_get_query_multivalued_param(self, httpbin):497498 r = requests.get(httpbin('get'), params=dict(test=['foo', 'baz']))499 assert r.status_code == 200500 assert r.url == httpbin('get?test=foo&test=baz')501502 def test_different_encodings_dont_break_post(self, httpbin):503 r = requests.post(httpbin('post'),504 data={'stuff': json.dumps({'a': 123})},505 params={'blah': 'asdf1234'},506 files={'file': ('test_requests.py', open(__file__, 'rb'))})507 assert r.status_code == 200508509 @pytest.mark.parametrize(510 'data', (511 {'stuff': u('ëlïxr')},512 {'stuff': u('ëlïxr').encode('utf-8')},513 {'stuff': 'elixr'},514 {'stuff': 'elixr'.encode('utf-8')},515 ))516 def test_unicode_multipart_post(self, httpbin, data):517 r = requests.post(httpbin('post'),518 data=data,519 files={'file': ('test_requests.py', open(__file__, 'rb'))})520 assert r.status_code == 200521522 def test_unicode_multipart_post_fieldnames(self, httpbin):523 filename = os.path.splitext(__file__)[0] + '.py'524 r = requests.Request(525 method='POST', url=httpbin('post'),526 data={'stuff'.encode('utf-8'): 'elixr'},527 files={'file': ('test_requests.py', open(filename, 'rb'))})528 prep = r.prepare()529 assert b'name="stuff"' in prep.body530 assert b'name="b\'stuff\'"' not in prep.body531532 def test_unicode_method_name(self, httpbin):533 files = {'file': open(__file__, 'rb')}534 r = requests.request(535 method=u('POST'), url=httpbin('post'), files=files)536 assert r.status_code == 200537538 def test_unicode_method_name_with_request_object(self, httpbin):539 files = {'file': open(__file__, 'rb')}540 s = requests.Session()541 req = requests.Request(u('POST'), httpbin('post'), files=files)542 prep = s.prepare_request(req)543 assert isinstance(prep.method, builtin_str)544 assert prep.method == 'POST'545546 resp = s.send(prep)547 assert resp.status_code == 200548549 def test_custom_content_type(self, httpbin):550 r = requests.post(551 httpbin('post'),552 data={'stuff': json.dumps({'a': 123})},553 files={554 'file1': ('test_requests.py', open(__file__, 'rb')),555 'file2': ('test_requests', open(__file__, 'rb'),556 'text/py-content-type')})557 assert r.status_code == 200558 assert b"text/py-content-type" in r.request.body559560 def test_hook_receives_request_arguments(self, httpbin):561 def hook(resp, **kwargs):562 assert resp is not None563 assert kwargs != {}564565 s = requests.Session()566 r = requests.Request('GET', httpbin(), hooks={'response': hook})567 prep = s.prepare_request(r)568 s.send(prep)569570 def test_session_hooks_are_used_with_no_request_hooks(self, httpbin):571 hook = lambda x, *args, **kwargs: x572 s = requests.Session()573 s.hooks['response'].append(hook)574 r = requests.Request('GET', httpbin())575 prep = s.prepare_request(r)576 assert prep.hooks['response'] != []577 assert prep.hooks['response'] == [hook]578579 def test_session_hooks_are_overridden_by_request_hooks(self, httpbin):580 hook1 = lambda x, *args, **kwargs: x581 hook2 = lambda x, *args, **kwargs: x582 assert hook1 is not hook2583 s = requests.Session()584 s.hooks['response'].append(hook2)585 r = requests.Request('GET', httpbin(), hooks={'response': [hook1]})586 prep = s.prepare_request(r)587 assert prep.hooks['response'] == [hook1]588589 def test_prepared_request_hook(self, httpbin):590 def hook(resp, **kwargs):591 resp.hook_working = True592 return resp593594 req = requests.Request('GET', httpbin(), hooks={'response': hook})595 prep = req.prepare()596597 s = requests.Session()598 s.proxies = getproxies()599 resp = s.send(prep)600601 assert hasattr(resp, 'hook_working')602603 def test_prepared_from_session(self, httpbin):604 class DummyAuth(requests.auth.AuthBase):605 def __call__(self, r):606 r.headers['Dummy-Auth-Test'] = 'dummy-auth-test-ok'607 return r608609 req = requests.Request('GET', httpbin('headers'))610 assert not req.auth611612 s = requests.Session()613 s.auth = DummyAuth()614615 prep = s.prepare_request(req)616 resp = s.send(prep)617618 assert resp.json()['headers'][619 'Dummy-Auth-Test'] == 'dummy-auth-test-ok'620621 def test_prepare_request_with_bytestring_url(self):622 req = requests.Request('GET', b'https://httpbin.org/')623 s = requests.Session()624 prep = s.prepare_request(req)625 assert prep.url == "https://httpbin.org/"626627 def test_links(self):628 r = requests.Response()629 r.headers = {630 'cache-control': 'public, max-age=60, s-maxage=60',631 'connection': 'keep-alive',632 'content-encoding': 'gzip',633 'content-type': 'application/json; charset=utf-8',634 'date': 'Sat, 26 Jan 2013 16:47:56 GMT',635 'etag': '"6ff6a73c0e446c1f61614769e3ceb778"',636 'last-modified': 'Sat, 26 Jan 2013 16:22:39 GMT',637 'link': ('<https://api.github.com/users/kennethreitz/repos?'638 'page=2&per_page=10>; rel="next", <https://api.github.'639 'com/users/kennethreitz/repos?page=7&per_page=10>; '640 ' rel="last"'),641 'server': 'GitHub.com',642 'status': '200 OK',643 'vary': 'Accept',644 'x-content-type-options': 'nosniff',645 'x-github-media-type': 'github.beta',646 'x-ratelimit-limit': '60',647 'x-ratelimit-remaining': '57'648 }649 assert r.links['next']['rel'] == 'next'650651 def test_cookie_parameters(self):652 key = 'some_cookie'653 value = 'some_value'654 secure = True655 domain = 'test.com'656 rest = {'HttpOnly': True}657658 jar = requests.cookies.RequestsCookieJar()659 jar.set(key, value, secure=secure, domain=domain, rest=rest)660661 assert len(jar) == 1662 assert 'some_cookie' in jar663664 cookie = list(jar)[0]665 assert cookie.secure == secure666 assert cookie.domain == domain667 assert cookie._rest['HttpOnly'] == rest['HttpOnly']668669 def test_cookie_as_dict_keeps_len(self):670 key = 'some_cookie'671 value = 'some_value'672673 key1 = 'some_cookie1'674 value1 = 'some_value1'675676 jar = requests.cookies.RequestsCookieJar()677 jar.set(key, value)678 jar.set(key1, value1)679680 d1 = dict(jar)681 d2 = dict(jar.iteritems())682 d3 = dict(jar.items())683684 assert len(jar) == 2685 assert len(d1) == 2686 assert len(d2) == 2687 assert len(d3) == 2688689 def test_cookie_as_dict_keeps_items(self):690 key = 'some_cookie'691 value = 'some_value'692693 key1 = 'some_cookie1'694 value1 = 'some_value1'695696 jar = requests.cookies.RequestsCookieJar()697 jar.set(key, value)698 jar.set(key1, value1)699700 d1 = dict(jar)701 d2 = dict(jar.iteritems())702 d3 = dict(jar.items())703704 assert d1['some_cookie'] == 'some_value'705 assert d2['some_cookie'] == 'some_value'706 assert d3['some_cookie1'] == 'some_value1'707708 def test_cookie_as_dict_keys(self):709 key = 'some_cookie'710 value = 'some_value'711712 key1 = 'some_cookie1'713 value1 = 'some_value1'714715 jar = requests.cookies.RequestsCookieJar()716 jar.set(key, value)717 jar.set(key1, value1)718719 keys = jar.keys()720 assert keys == list(keys)721 # make sure one can use keys multiple times722 assert list(keys) == list(keys)723724 def test_cookie_as_dict_values(self):725 key = 'some_cookie'726 value = 'some_value'727728 key1 = 'some_cookie1'729 value1 = 'some_value1'730731 jar = requests.cookies.RequestsCookieJar()732 jar.set(key, value)733 jar.set(key1, value1)734735 values = jar.values()736 assert values == list(values)737 # make sure one can use values multiple times738 assert list(values) == list(values)739740 def test_cookie_as_dict_items(self):741 key = 'some_cookie'742 value = 'some_value'743744 key1 = 'some_cookie1'745 value1 = 'some_value1'746747 jar = requests.cookies.RequestsCookieJar()748 jar.set(key, value)749 jar.set(key1, value1)750751 items = jar.items()752 assert items == list(items)753 # make sure one can use items multiple times754 assert list(items) == list(items)755756 def test_time_elapsed_blank(self, httpbin):757 r = requests.get(httpbin('get'))758 td = r.elapsed759 total_seconds = ((td.microseconds + (td.seconds + td.days * 24 * 3600)760 * 10**6) / 10**6)761 assert total_seconds > 0.0762763 def test_response_is_iterable(self):764 r = requests.Response()765 io = StringIO.StringIO('abc')766 read_ = io.read767768 def read_mock(amt, decode_content=None):769 return read_(amt)770 setattr(io, 'read', read_mock)771 r.raw = io772 assert next(iter(r))773 io.close()774775 def test_response_decode_unicode(self):776 """777 When called with decode_unicode, Response.iter_content should always778 return unicode.779 """780 r = requests.Response()781 r._content_consumed = True782 r._content = b'the content'783 r.encoding = 'ascii'784785 chunks = r.iter_content(decode_unicode=True)786 assert all(isinstance(chunk, str) for chunk in chunks)787788 # also for streaming789 r = requests.Response()790 r.raw = io.BytesIO(b'the content')791 r.encoding = 'ascii'792 chunks = r.iter_content(decode_unicode=True)793 assert all(isinstance(chunk, str) for chunk in chunks)794795 def test_request_and_response_are_pickleable(self, httpbin):796 r = requests.get(httpbin('get'))797798 # verify we can pickle the original request799 assert pickle.loads(pickle.dumps(r.request))800801 # verify we can pickle the response and that we have access to802 # the original request.803 pr = pickle.loads(pickle.dumps(r))804 assert r.request.url == pr.request.url805 assert r.request.headers == pr.request.headers806807 def test_cannot_send_unprepared_requests(self, httpbin):808 r = requests.Request(url=httpbin())809 with pytest.raises(ValueError):810 requests.Session().send(r)811812 def test_http_error(self):813 error = requests.exceptions.HTTPError()814 assert not error.response815 response = requests.Response()816 error = requests.exceptions.HTTPError(response=response)817 assert error.response == response818 error = requests.exceptions.HTTPError('message', response=response)819 assert str(error) == 'message'820 assert error.response == response821822 def test_session_pickling(self, httpbin):823 r = requests.Request('GET', httpbin('get'))824 s = requests.Session()825826 s = pickle.loads(pickle.dumps(s))827 s.proxies = getproxies()828829 r = s.send(r.prepare())830 assert r.status_code == 200831832 def test_fixes_1329(self, httpbin):833 """834 Ensure that header updates are done case-insensitively.835 """836 s = requests.Session()837 s.headers.update({'ACCEPT': 'BOGUS'})838 s.headers.update({'accept': 'application/json'})839 r = s.get(httpbin('get'))840 headers = r.request.headers841 assert headers['accept'] == 'application/json'842 assert headers['Accept'] == 'application/json'843 assert headers['ACCEPT'] == 'application/json'844845 def test_uppercase_scheme_redirect(self, httpbin):846 parts = urlparse(httpbin('html'))847 url = "HTTP://" + parts.netloc + parts.path848 r = requests.get(httpbin('redirect-to'), params={'url': url})849 assert r.status_code == 200850 assert r.url.lower() == url.lower()851852 def test_transport_adapter_ordering(self):853 s = requests.Session()854 order = ['https://', 'http://']855 assert order == list(s.adapters)856 s.mount('http://git', HTTPAdapter())857 s.mount('http://github', HTTPAdapter())858 s.mount('http://github.com', HTTPAdapter())859 s.mount('http://github.com/about/', HTTPAdapter())860 order = [861 'http://github.com/about/',862 'http://github.com',863 'http://github',864 'http://git',865 'https://',866 'http://',867 ]868 assert order == list(s.adapters)869 s.mount('http://gittip', HTTPAdapter())870 s.mount('http://gittip.com', HTTPAdapter())871 s.mount('http://gittip.com/about/', HTTPAdapter())872 order = [873 'http://github.com/about/',874 'http://gittip.com/about/',875 'http://github.com',876 'http://gittip.com',877 'http://github',878 'http://gittip',879 'http://git',880 'https://',881 'http://',882 ]883 assert order == list(s.adapters)884 s2 = requests.Session()885 s2.adapters = {'http://': HTTPAdapter()}886 s2.mount('https://', HTTPAdapter())887 assert 'http://' in s2.adapters888 assert 'https://' in s2.adapters889890 def test_header_remove_is_case_insensitive(self, httpbin):891 # From issue #1321892 s = requests.Session()893 s.headers['foo'] = 'bar'894 r = s.get(httpbin('get'), headers={'FOO': None})895 assert 'foo' not in r.request.headers896897 def test_params_are_merged_case_sensitive(self, httpbin):898 s = requests.Session()899 s.params['foo'] = 'bar'900 r = s.get(httpbin('get'), params={'FOO': 'bar'})901 assert r.json()['args'] == {'foo': 'bar', 'FOO': 'bar'}902903 def test_long_authinfo_in_url(self):904 url = 'http://{0}:{1}@{2}:9000/path?query#frag'.format(905 'E8A3BE87-9E3F-4620-8858-95478E385B5B',906 'EA770032-DA4D-4D84-8CE9-29C6D910BF1E',907 'exactly-------------sixty-----------three------------characters',908 )909 r = requests.Request('GET', url).prepare()910 assert r.url == url911912 def test_header_keys_are_native(self, httpbin):913 headers = {u('unicode'): 'blah', 'byte'.encode('ascii'): 'blah'}914 r = requests.Request('GET', httpbin('get'), headers=headers)915 p = r.prepare()916917 # This is testing that they are builtin strings. A bit weird, but there918 # we go.919 assert 'unicode' in p.headers.keys()920 assert 'byte' in p.headers.keys()921922 @pytest.mark.parametrize('files', ('foo', b'foo', bytearray(b'foo')))923 def test_can_send_objects_with_files(self, httpbin, files):924 data = {'a': 'this is a string'}925 files = {'b': files}926 r = requests.Request('POST', httpbin('post'), data=data, files=files)927 p = r.prepare()928 assert 'multipart/form-data' in p.headers['Content-Type']929930 def test_can_send_file_object_with_non_string_filename(self, httpbin):931 f = io.BytesIO()932 f.name = 2933 r = requests.Request('POST', httpbin('post'), files={'f': f})934 p = r.prepare()935936 assert 'multipart/form-data' in p.headers['Content-Type']937938 def test_autoset_header_values_are_native(self, httpbin):939 data = 'this is a string'940 length = '16'941 req = requests.Request('POST', httpbin('post'), data=data)942 p = req.prepare()943944 assert p.headers['Content-Length'] == length945946 def test_nonhttp_schemes_dont_check_URLs(self):947 test_urls = (948 'data:image/gif;base64,R0lGODlhAQABAHAAACH5BAUAAAAALAAAAAABAAEAAAICRAEAOw==',949 'file:///etc/passwd',950 'magnet:?xt=urn:btih:be08f00302bc2d1d3cfa3af02024fa647a271431',951 )952 for test_url in test_urls:953 req = requests.Request('GET', test_url)954 preq = req.prepare()955 assert test_url == preq.url956957 def test_auth_is_stripped_on_redirect_off_host(self, httpbin):958 r = requests.get(959 httpbin('redirect-to'),960 params={'url': 'http://www.google.co.uk'},961 auth=('user', 'pass'),962 )963 assert r.history[0].request.headers['Authorization']964 assert not r.request.headers.get('Authorization', '')965966 def test_auth_is_retained_for_redirect_on_host(self, httpbin):967 r = requests.get(httpbin('redirect/1'), auth=('user', 'pass'))968 h1 = r.history[0].request.headers['Authorization']969 h2 = r.request.headers['Authorization']970971 assert h1 == h2972973 def test_manual_redirect_with_partial_body_read(self, httpbin):974 s = requests.Session()975 r1 = s.get(httpbin('redirect/2'), allow_redirects=False, stream=True)976 assert r1.is_redirect977 rg = s.resolve_redirects(r1, r1.request, stream=True)978979 # read only the first eight bytes of the response body,980 # then follow the redirect981 r1.iter_content(8)982 r2 = next(rg)983 assert r2.is_redirect984985 # read all of the response via iter_content,986 # then follow the redirect987 for _ in r2.iter_content():988 pass989 r3 = next(rg)990 assert not r3.is_redirect991992 def _patch_adapter_gzipped_redirect(self, session, url):993 adapter = session.get_adapter(url=url)994 org_build_response = adapter.build_response995 self._patched_response = False996997 def build_response(*args, **kwargs):998 resp = org_build_response(*args, **kwargs)999 if not self._patched_response:1000 resp.raw.headers['content-encoding'] = 'gzip'1001 self._patched_response = True1002 return resp10031004 adapter.build_response = build_response10051006 def test_redirect_with_wrong_gzipped_header(self, httpbin):1007 s = requests.Session()1008 url = httpbin('redirect/1')1009 self._patch_adapter_gzipped_redirect(s, url)1010 s.get(url)10111012 def test_basic_auth_str_is_always_native(self):1013 s = _basic_auth_str("test", "test")1014 assert isinstance(s, builtin_str)1015 assert s == "Basic dGVzdDp0ZXN0"10161017 def test_requests_history_is_saved(self, httpbin):1018 r = requests.get(httpbin('redirect/5'))1019 total = r.history[-1].history1020 i = 01021 for item in r.history:1022 assert item.history == total[0:i]1023 i += 110241025 def test_json_param_post_content_type_works(self, httpbin):1026 r = requests.post(1027 httpbin('post'),1028 json={'life': 42}1029 )1030 assert r.status_code == 2001031 assert 'application/json' in r.request.headers['Content-Type']1032 assert {'life': 42} == r.json()['json']10331034 def test_json_param_post_should_not_override_data_param(self, httpbin):1035 r = requests.Request(method='POST', url=httpbin('post'),1036 data={'stuff': 'elixr'},1037 json={'music': 'flute'})1038 prep = r.prepare()1039 assert 'stuff=elixr' == prep.body10401041 def test_response_iter_lines(self, httpbin):1042 r = requests.get(httpbin('stream/4'), stream=True)1043 assert r.status_code == 20010441045 it = r.iter_lines()1046 next(it)1047 assert len(list(it)) == 310481049 def test_unconsumed_session_response_closes_connection(self, httpbin):1050 s = requests.session()10511052 with contextlib.closing(s.get(httpbin('stream/4'), stream=True)) as response:1053 pass10541055 assert response._content_consumed is False1056 assert response.raw.closed10571058 @pytest.mark.xfail1059 def test_response_iter_lines_reentrant(self, httpbin):1060 """Response.iter_lines() is not reentrant safe"""1061 r = requests.get(httpbin('stream/4'), stream=True)1062 assert r.status_code == 20010631064 next(r.iter_lines())1065 assert len(list(r.iter_lines())) == 3106610671068class TestCaseInsensitiveDict:10691070 @pytest.mark.parametrize(1071 'cid', (1072 CaseInsensitiveDict({'Foo': 'foo', 'BAr': 'bar'}),1073 CaseInsensitiveDict([('Foo', 'foo'), ('BAr', 'bar')]),1074 CaseInsensitiveDict(FOO='foo', BAr='bar'),1075 ))1076 def test_init(self, cid):1077 assert len(cid) == 21078 assert 'foo' in cid1079 assert 'bar' in cid10801081 def test_docstring_example(self):1082 cid = CaseInsensitiveDict()1083 cid['Accept'] = 'application/json'1084 assert cid['aCCEPT'] == 'application/json'1085 assert list(cid) == ['Accept']10861087 def test_len(self):1088 cid = CaseInsensitiveDict({'a': 'a', 'b': 'b'})1089 cid['A'] = 'a'1090 assert len(cid) == 210911092 def test_getitem(self):1093 cid = CaseInsensitiveDict({'Spam': 'blueval'})1094 assert cid['spam'] == 'blueval'1095 assert cid['SPAM'] == 'blueval'10961097 def test_fixes_649(self):1098 """__setitem__ should behave case-insensitively."""1099 cid = CaseInsensitiveDict()1100 cid['spam'] = 'oneval'1101 cid['Spam'] = 'twoval'1102 cid['sPAM'] = 'redval'1103 cid['SPAM'] = 'blueval'1104 assert cid['spam'] == 'blueval'1105 assert cid['SPAM'] == 'blueval'1106 assert list(cid.keys()) == ['SPAM']11071108 def test_delitem(self):1109 cid = CaseInsensitiveDict()1110 cid['Spam'] = 'someval'1111 del cid['sPam']1112 assert 'spam' not in cid1113 assert len(cid) == 011141115 def test_contains(self):1116 cid = CaseInsensitiveDict()1117 cid['Spam'] = 'someval'1118 assert 'Spam' in cid1119 assert 'spam' in cid1120 assert 'SPAM' in cid1121 assert 'sPam' in cid1122 assert 'notspam' not in cid11231124 def test_get(self):1125 cid = CaseInsensitiveDict()1126 cid['spam'] = 'oneval'1127 cid['SPAM'] = 'blueval'1128 assert cid.get('spam') == 'blueval'1129 assert cid.get('SPAM') == 'blueval'1130 assert cid.get('sPam') == 'blueval'1131 assert cid.get('notspam', 'default') == 'default'11321133 def test_update(self):1134 cid = CaseInsensitiveDict()1135 cid['spam'] = 'blueval'1136 cid.update({'sPam': 'notblueval'})1137 assert cid['spam'] == 'notblueval'1138 cid = CaseInsensitiveDict({'Foo': 'foo', 'BAr': 'bar'})1139 cid.update({'fOO': 'anotherfoo', 'bAR': 'anotherbar'})1140 assert len(cid) == 21141 assert cid['foo'] == 'anotherfoo'1142 assert cid['bar'] == 'anotherbar'11431144 def test_update_retains_unchanged(self):1145 cid = CaseInsensitiveDict({'foo': 'foo', 'bar': 'bar'})1146 cid.update({'foo': 'newfoo'})1147 assert cid['bar'] == 'bar'11481149 def test_iter(self):1150 cid = CaseInsensitiveDict({'Spam': 'spam', 'Eggs': 'eggs'})1151 keys = frozenset(['Spam', 'Eggs'])1152 assert frozenset(iter(cid)) == keys11531154 def test_equality(self):1155 cid = CaseInsensitiveDict({'SPAM': 'blueval', 'Eggs': 'redval'})1156 othercid = CaseInsensitiveDict({'spam': 'blueval', 'eggs': 'redval'})1157 assert cid == othercid1158 del othercid['spam']1159 assert cid != othercid1160 assert cid == {'spam': 'blueval', 'eggs': 'redval'}1161 assert cid != object()11621163 def test_setdefault(self):1164 cid = CaseInsensitiveDict({'Spam': 'blueval'})1165 assert cid.setdefault('spam', 'notblueval') == 'blueval'1166 assert cid.setdefault('notspam', 'notblueval') == 'notblueval'11671168 def test_lower_items(self):1169 cid = CaseInsensitiveDict({1170 'Accept': 'application/json',1171 'user-Agent': 'requests',1172 })1173 keyset = frozenset(lowerkey for lowerkey, v in cid.lower_items())1174 lowerkeyset = frozenset(['accept', 'user-agent'])1175 assert keyset == lowerkeyset11761177 def test_preserve_key_case(self):1178 cid = CaseInsensitiveDict({1179 'Accept': 'application/json',1180 'user-Agent': 'requests',1181 })1182 keyset = frozenset(['Accept', 'user-Agent'])1183 assert frozenset(i[0] for i in cid.items()) == keyset1184 assert frozenset(cid.keys()) == keyset1185 assert frozenset(cid) == keyset11861187 def test_preserve_last_key_case(self):1188 cid = CaseInsensitiveDict({1189 'Accept': 'application/json',1190 'user-Agent': 'requests',1191 })1192 cid.update({'ACCEPT': 'application/json'})1193 cid['USER-AGENT'] = 'requests'1194 keyset = frozenset(['ACCEPT', 'USER-AGENT'])1195 assert frozenset(i[0] for i in cid.items()) == keyset1196 assert frozenset(cid.keys()) == keyset1197 assert frozenset(cid) == keyset11981199 def test_copy(self):1200 cid = CaseInsensitiveDict({1201 'Accept': 'application/json',1202 'user-Agent': 'requests',1203 })1204 cid_copy = cid.copy()1205 assert cid == cid_copy1206 cid['changed'] = True1207 assert cid != cid_copy120812091210class TestMorselToCookieExpires:1211 """Tests for morsel_to_cookie when morsel contains expires."""12121213 def test_expires_valid_str(self):1214 """Test case where we convert expires from string time."""12151216 morsel = Morsel()1217 morsel['expires'] = 'Thu, 01-Jan-1970 00:00:01 GMT'1218 cookie = morsel_to_cookie(morsel)1219 assert cookie.expires == 112201221 @pytest.mark.parametrize(1222 'value, exception', (1223 (100, TypeError),1224 ('woops', ValueError),1225 ))1226 def test_expires_invalid_int(self, value, exception):1227 """Test case where an invalid type is passed for expires."""1228 morsel = Morsel()1229 morsel['expires'] = value1230 with pytest.raises(exception):1231 morsel_to_cookie(morsel)12321233 def test_expires_none(self):1234 """Test case where expires is None."""12351236 morsel = Morsel()1237 morsel['expires'] = None1238 cookie = morsel_to_cookie(morsel)1239 assert cookie.expires is None124012411242class TestMorselToCookieMaxAge:12431244 """Tests for morsel_to_cookie when morsel contains max-age."""12451246 def test_max_age_valid_int(self):1247 """Test case where a valid max age in seconds is passed."""12481249 morsel = Morsel()1250 morsel['max-age'] = 601251 cookie = morsel_to_cookie(morsel)1252 assert isinstance(cookie.expires, int)12531254 def test_max_age_invalid_str(self):1255 """Test case where a invalid max age is passed."""12561257 morsel = Morsel()1258 morsel['max-age'] = 'woops'1259 with pytest.raises(TypeError):1260 morsel_to_cookie(morsel)126112621263class TestTimeout:12641265 def test_stream_timeout(self, httpbin):1266 try:1267 requests.get(httpbin('delay/10'), timeout=2.0)1268 except requests.exceptions.Timeout as e:1269 assert 'Read timed out' in e.args[0].args[0]12701271 @pytest.mark.parametrize(1272 'timeout, error_text', (1273 ((3, 4, 5), '(connect, read)'),1274 ('foo', 'must be an int or float'),1275 ))1276 def test_invalid_timeout(self, httpbin, timeout, error_text):1277 with pytest.raises(ValueError) as e:1278 requests.get(httpbin('get'), timeout=timeout)1279 assert error_text in str(e)12801281 def test_none_timeout(self, httpbin):1282 """ Check that you can set None as a valid timeout value.12831284 To actually test this behavior, we'd want to check that setting the1285 timeout to None actually lets the request block past the system default1286 timeout. However, this would make the test suite unbearably slow.1287 Instead we verify that setting the timeout to None does not prevent the1288 request from succeeding.1289 """1290 r = requests.get(httpbin('get'), timeout=None)1291 assert r.status_code == 20012921293 def test_read_timeout(self, httpbin):1294 try:1295 requests.get(httpbin('delay/10'), timeout=(None, 0.1))1296 pytest.fail('The recv() request should time out.')1297 except ReadTimeout:1298 pass12991300 def test_connect_timeout(self):1301 try:1302 requests.get(TARPIT, timeout=(0.1, None))1303 pytest.fail('The connect() request should time out.')1304 except ConnectTimeout as e:1305 assert isinstance(e, ConnectionError)1306 assert isinstance(e, Timeout)13071308 def test_total_timeout_connect(self):1309 try:1310 requests.get(TARPIT, timeout=(0.1, 0.1))1311 pytest.fail('The connect() request should time out.')1312 except ConnectTimeout:1313 pass13141315 def test_encoded_methods(self, httpbin):1316 """See: https://github.com/kennethreitz/requests/issues/2316"""1317 r = requests.request(b'GET', httpbin('get'))1318 assert r.ok131913201321SendCall = collections.namedtuple('SendCall', ('args', 'kwargs'))132213231324class RedirectSession(SessionRedirectMixin):1325 def __init__(self, order_of_redirects):1326 self.redirects = order_of_redirects1327 self.calls = []1328 self.max_redirects = 301329 self.cookies = {}1330 self.trust_env = False13311332 def send(self, *args, **kwargs):1333 self.calls.append(SendCall(args, kwargs))1334 return self.build_response()13351336 def build_response(self):1337 request = self.calls[-1].args[0]1338 r = requests.Response()13391340 try:1341 r.status_code = int(self.redirects.pop(0))1342 except IndexError:1343 r.status_code = 20013441345 r.headers = CaseInsensitiveDict({'Location': '/'})1346 r.raw = self._build_raw()1347 r.request = request1348 return r13491350 def _build_raw(self):1351 string = StringIO.StringIO('')1352 setattr(string, 'release_conn', lambda *args: args)1353 return string135413551356def test_requests_are_updated_each_time(httpbin):1357 session = RedirectSession([303, 307])1358 prep = requests.Request('POST', httpbin('post')).prepare()1359 r0 = session.send(prep)1360 assert r0.request.method == 'POST'1361 assert session.calls[-1] == SendCall((r0.request,), {})1362 redirect_generator = session.resolve_redirects(r0, prep)1363 default_keyword_args = {1364 'stream': False,1365 'verify': True,1366 'cert': None,1367 'timeout': None,1368 'allow_redirects': False,1369 'proxies': {},1370 }1371 for response in redirect_generator:1372 assert response.request.method == 'GET'1373 send_call = SendCall((response.request,), default_keyword_args)1374 assert session.calls[-1] == send_call137513761377@pytest.mark.parametrize(1378 'data', (1379 (('a', 'b'), ('c', 'd')),1380 (('c', 'd'), ('a', 'b')),1381 (('a', 'b'), ('c', 'd'), ('e', 'f')),1382 ))1383def test_data_argument_accepts_tuples(data):1384 """Ensure that the data argument will accept tuples of strings1385 and properly encode them.1386 """1387 p = PreparedRequest()1388 p.prepare(1389 method='GET',1390 url='http://www.example.com',1391 data=data,1392 hooks=default_hooks()1393 )1394 assert p.body == urlencode(data)139513961397@pytest.mark.parametrize(1398 'kwargs', (1399 None,1400 {1401 'method': 'GET',1402 'url': 'http://www.example.com',1403 'data': 'foo=bar',1404 'hooks': default_hooks()1405 },1406 {1407 'method': 'GET',1408 'url': 'http://www.example.com',1409 'data': 'foo=bar',1410 'hooks': default_hooks(),1411 'cookies': {'foo': 'bar'}1412 },1413 {1414 'method': 'GET',1415 'url': u('http://www.example.com/üniçø∂é')1416 },1417 ))1418def test_prepared_copy(kwargs):1419 p = PreparedRequest()1420 if kwargs:1421 p.prepare(**kwargs)1422 copy = p.copy()1423 for attr in ('method', 'url', 'headers', '_cookies', 'body', 'hooks'):1424 assert getattr(p, attr) == getattr(copy, attr)142514261427def test_urllib3_retries(httpbin):1428 from requests.packages.urllib3.util import Retry1429 s = requests.Session()1430 s.mount('http://', HTTPAdapter(max_retries=Retry(1431 total=2, status_forcelist=[500]1432 )))14331434 with pytest.raises(RetryError):1435 s.get(httpbin('status/500'))143614371438def test_urllib3_pool_connection_closed(httpbin):1439 s = requests.Session()1440 s.mount('http://', HTTPAdapter(pool_connections=0, pool_maxsize=0))14411442 try:1443 s.get(httpbin('status/200'))1444 except ConnectionError as e:1445 assert u"Pool is closed." in str(e)144614471448def test_vendor_aliases():1449 from requests.packages import urllib31450 from requests.packages import chardet14511452 with pytest.raises(ImportError):1453 from requests.packages import webbrowser1454145514561457if __name__ == '__main__':1458 unittest.main()
added:tests/test_utils.py+374 added
1# coding: utf-82import os3import threading4import socket5import time6from io import BytesIO78import pytest9import requests10from requests import compat11from requests.utils import (12 address_in_network, dotted_netmask,13 get_auth_from_url, get_encodings_from_content,14 get_environ_proxies, guess_filename,15 is_ipv4_address, is_valid_cidr, requote_uri,16 select_proxy, super_len)1718from .compat import StringIO, cStringIO1920from testserver.server import Server212223class TestSuperLen:2425 @pytest.mark.parametrize(26 'stream, value', (27 (StringIO.StringIO, 'Test'),28 (BytesIO, b'Test'),29 pytest.mark.skipif('cStringIO is None')((cStringIO, 'Test')),30 ))31 def test_io_streams(self, stream, value):32 """Ensures that we properly deal with different kinds of IO streams."""33 assert super_len(stream()) == 034 assert super_len(stream(value)) == 43536 def test_super_len_correctly_calculates_len_of_partially_read_file(self):37 """Ensure that we handle partially consumed file like objects."""38 s = StringIO.StringIO()39 s.write('foobarbogus')40 assert super_len(s) == 0414243class TestGetEnvironProxies:44 """Ensures that IP addresses are correctly matches with ranges45 in no_proxy variable."""4647 @pytest.yield_fixture(scope='class', autouse=True, params=['no_proxy', 'NO_PROXY'])48 def no_proxy(self, request):49 os.environ[request.param] = '192.168.0.0/24,127.0.0.1,localhost.localdomain,172.16.1.1'50 yield51 del os.environ[request.param]5253 @pytest.mark.parametrize(54 'url', (55 'http://192.168.0.1:5000/',56 'http://192.168.0.1/',57 'http://172.16.1.1/',58 'http://172.16.1.1:5000/',59 'http://localhost.localdomain:5000/v1.0/',60 ))61 def test_bypass(self, url):62 assert get_environ_proxies(url) == {}6364 @pytest.mark.parametrize(65 'url', (66 'http://192.168.1.1:5000/',67 'http://192.168.1.1/',68 'http://www.requests.com/',69 ))70 def test_not_bypass(self, url):71 assert get_environ_proxies(url) != {}727374class TestIsIPv4Address:7576 def test_valid(self):77 assert is_ipv4_address('8.8.8.8')7879 @pytest.mark.parametrize('value', ('8.8.8.8.8', 'localhost.localdomain'))80 def test_invalid(self, value):81 assert not is_ipv4_address(value)828384class TestIsValidCIDR:8586 def test_valid(self):87 assert is_valid_cidr('192.168.1.0/24')8889 @pytest.mark.parametrize(90 'value', (91 '8.8.8.8',92 '192.168.1.0/a',93 '192.168.1.0/128',94 '192.168.1.0/-1',95 '192.168.1.999/24',96 ))97 def test_invalid(self, value):98 assert not is_valid_cidr(value)99100101class TestAddressInNetwork:102103 def test_valid(self):104 assert address_in_network('192.168.1.1', '192.168.1.0/24')105106 def test_invalid(self):107 assert not address_in_network('172.16.0.1', '192.168.1.0/24')108109110class TestGuessFilename:111112 @pytest.mark.parametrize(113 'value', (1, type('Fake', (object,), {'name': 1})()),114 )115 def test_guess_filename_invalid(self, value):116 assert guess_filename(value) is None117118 @pytest.mark.parametrize(119 'value, expected_type', (120 (b'value', compat.bytes),121 (b'value'.decode('utf-8'), compat.str)122 ))123 def test_guess_filename_valid(self, value, expected_type):124 obj = type('Fake', (object,), {'name': value})()125 result = guess_filename(obj)126 assert result == value127 assert isinstance(result, expected_type)128129130class TestContentEncodingDetection:131132 def test_none(self):133 encodings = get_encodings_from_content('')134 assert not len(encodings)135136 @pytest.mark.parametrize(137 'content', (138 # HTML5 meta charset attribute139 '<meta charset="UTF-8">',140 # HTML4 pragma directive141 '<meta http-equiv="Content-type" content="text/html;charset=UTF-8">',142 # XHTML 1.x served with text/html MIME type143 '<meta http-equiv="Content-type" content="text/html;charset=UTF-8" />',144 # XHTML 1.x served as XML145 '<?xml version="1.0" encoding="UTF-8"?>',146 ))147 def test_pragmas(self, content):148 encodings = get_encodings_from_content(content)149 assert len(encodings) == 1150 assert encodings[0] == 'UTF-8'151152 def test_precedence(self):153 content = '''154 <?xml version="1.0" encoding="XML"?>155 <meta charset="HTML5">156 <meta http-equiv="Content-type" content="text/html;charset=HTML4" />157 '''.strip()158 assert get_encodings_from_content(content) == ['HTML5', 'HTML4', 'XML']159160 def test_chunked_upload(self):161 """can safely send generators"""162 block_server = threading.Event()163 server = Server.basic_response_server(wait_to_close_event=block_server)164 data = (i for i in [b'a', b'b', b'c']) 165166 with server as (host, port):167 url = 'http://{}:{}/'.format(host, port)168 r = requests.post(url, data=data, stream=True)169 block_server.set() # release server block170171 assert r.status_code == 200172 assert r.request.headers['Transfer-Encoding'] == 'chunked'173174175176177USER = PASSWORD = "%!*'();:@&=+$,/?#[] "178ENCODED_USER = compat.quote(USER, '')179ENCODED_PASSWORD = compat.quote(PASSWORD, '')180181182@pytest.mark.parametrize(183 'url, auth', (184 (185 'http://' + ENCODED_USER + ':' + ENCODED_PASSWORD + '@' +186 'request.com/url.html#test',187 (USER, PASSWORD)188 ),189 (190 'http://user:pass@complex.url.com/path?query=yes',191 ('user', 'pass')192 ),193 (194 'http://user:pass%20pass@complex.url.com/path?query=yes',195 ('user', 'pass pass')196 ),197 (198 'http://user:pass pass@complex.url.com/path?query=yes',199 ('user', 'pass pass')200 ),201 (202 'http://user%25user:pass@complex.url.com/path?query=yes',203 ('user%user', 'pass')204 ),205 (206 'http://user:pass%23pass@complex.url.com/path?query=yes',207 ('user', 'pass#pass')208 ),209 ))210def test_get_auth_from_url(url, auth):211 assert get_auth_from_url(url) == auth212213214@pytest.mark.parametrize(215 'uri, expected', (216 (217 # Ensure requoting doesn't break expectations218 'http://example.com/fiz?buz=%25ppicture',219 'http://example.com/fiz?buz=%25ppicture',220 ),221 (222 # Ensure we handle unquoted percent signs in redirects223 'http://example.com/fiz?buz=%ppicture',224 'http://example.com/fiz?buz=%25ppicture',225 ),226 ))227def test_requote_uri_with_unquoted_percents(uri, expected):228 """See: https://github.com/kennethreitz/requests/issues/2356229 """230 assert requote_uri(uri) == expected231232233@pytest.mark.parametrize(234 'mask, expected', (235 (8, '255.0.0.0'),236 (24, '255.255.255.0'),237 (25, '255.255.255.128'),238 ))239def test_dotted_netmask(mask, expected):240 assert dotted_netmask(mask) == expected241242243@pytest.mark.parametrize(244 'url, expected', (245 ('hTTp://u:p@Some.Host/path', 'http://some.host.proxy'),246 ('hTTp://u:p@Other.Host/path', 'http://http.proxy'),247 ('hTTps://Other.Host', None),248 ))249def test_select_proxies(url, expected):250 """Make sure we can select per-host proxies correctly."""251 proxies = {'http': 'http://http.proxy',252 'http://some.host': 'http://some.host.proxy'}253 assert select_proxy(url, proxies) == expected254255class TestTestServer:256 def test_basic(self):257 question = b"sucess?"258 answer = b"yeah, success"259 def handler(sock):260 text = sock.recv(1000)261 assert text == question 262 sock.send(answer)263 264 with Server(handler) as (host, port):265 sock = socket.socket()266 sock.connect((host, port))267 sock.send(question)268 text = sock.recv(1000)269 assert text == answer270 sock.close()271272 def test_server_closes(self):273 with Server.basic_response_server() as (host, port):274 sock = socket.socket()275 sock.connect((host, port))276277 sock.close()278279 with pytest.raises(socket.error):280 new_sock = socket.socket()281 new_sock.connect((host, port))282283 def test_text_response(self):284 server = Server.text_response_server(285 "HTTP/1.1 200 OK\r\n" + 286 "Content-Length: 6\r\n" +287 "\r\nroflol"288 )289290 with server as (host, port):291 r = requests.get('http://{}:{}'.format(host, port))292293 assert r.status_code == 200294 assert r.text == 'roflol'295 assert r.headers['Content-Length'] == '6' 296 297 def test_basic_response(self):298 with Server.basic_response_server() as (host, port):299 r = requests.get('http://{}:{}'.format(host, port))300 assert r.status_code == 200301 assert r.text == ''302 assert r.headers['Content-Length'] == '0'303304 def test_basic_waiting_server(self):305 block_server = threading.Event()306307 with Server.basic_response_server(wait_to_close_event=block_server) as (host, port):308 sock = socket.socket()309 sock.connect((host, port))310 sock.send(b'send something')311 time.sleep(2.5)312 sock.send(b'still alive')313 block_server.set() # release server block314315 def test_multiple_requests(self):316 requests_to_handle = 5317 318 server = Server.basic_response_server(requests_to_handle=requests_to_handle)319320 with server as (host, port):321 server_url = 'http://{}:{}'.format(host, port)322 for _ in range(requests_to_handle):323 r = requests.get(server_url)324 assert r.status_code == 200325326 # the (n+1)th request fails327 with pytest.raises(requests.exceptions.ConnectionError):328 r = requests.get(server_url)329330 def test_request_recovery(self):331 server = Server.basic_response_server(requests_to_handle=2)332 first_request = "put your hands up in the air"333 second_request = "put your hand down in the floor"334335 with server as address:336 sock1 = socket.socket()337 sock2 = socket.socket()338 339 sock1.connect(address)340 sock1.send(first_request.encode())341 sock1.close()342343 sock2.connect(address)344 sock2.send(second_request.encode())345 sock2.close()346347 assert server.handler_results[0] == first_request348 assert server.handler_results[1] == second_request349350 def test_requests_after_timeout_are_not_received(self):351 server = Server.basic_response_server(request_timeout=1)352353 with server as address:354 sock = socket.socket()355 sock.connect(address)356 time.sleep(1.5)357 sock.send(b"hehehe, not received")358 sock.close()359360 assert server.handler_results[0] == ""361362363 def test_request_recovery_with_bigger_timeout(self):364 server = Server.basic_response_server(request_timeout=3)365 data = "bananadine"366367 with server as address:368 sock = socket.socket() 369 sock.connect(address)370 time.sleep(1.5)371 sock.send(data.encode())372 sock.close()373 374 assert server.handler_results[0] == data
modified:AUTHORS.rst+3 added-1 removed
132 unmodified lines
133- James Clarke (`@jam <https://github.com/jam>`_)134- Kevin Burke <kev@inburke.com>135- Flavio Curella136- David Pursehouse <david.pursehouse@gmail.com> (`@dpursehouse <https://github.com/dpursehouse>`_)137- Jon Parise137- Jon Parise (`@jparise <https://github.com/jparise>`_)138- Alexander Karpinsky (`@homm86 <https://twitter.com/homm86>`_)139- Marc Schlaich (`@schlamar <https://github.com/schlamar>`_)140- Park Ilsu <daftonshady@gmail.com> (`@daftshady <https://github.com/daftshady>`_)141- Matt Spitz (`@mattspitz <https://github.com/mattspitz>`_)
19 unmodified lines
161- Colin Dickson (`@colindickson <https://github.com/colindickson>`_)162- Smiley Barry (`@smiley <https://github.com/smiley>`_)163- Shagun Sodhani (`@shagunsodhani <https://github.com/shagunsodhani>`_)164- Robin Linderborg (`@vienno <https://github.com/vienno>`_)165- Brian Samek (`@bsamek <https://github.com/bsamek>`_)166- Dmitry Dygalo (`@Stranger6667 <https://github.com/Stranger6667>`_)
modified:HISTORY.rst+52 added-5 removed
1 unmodified line
23Release History4---------------56dev (XXXX)7++++++++++62.9.2 (???)7+++++++++++89**Bugfixes**1011- Don't use redirect_cache if allow_redirects=False12132.9.1 (2015-12-21)14++++++++++++++++++1516**Bugfixes**1718- Resolve regression introduced in 2.9.0 that made it impossible to send binary19 strings as bodies in Python 3.20- Fixed errors when calculating cookie expiration dates in certain locales.2122**Miscellaneous**2324- Updated bundled urllib3 to 1.13.1.25262.9.0 (2015-12-15)27++++++++++++++++++2829**Minor Improvements** (Backwards compatible)3031- The ``verify`` keyword argument now supports being passed a path to a32 directory of CA certificates, not just a single-file bundle.33- Warnings are now emitted when sending files opened in text mode.34- Added the 511 Network Authentication Required status code to the status code35 registry.3637**Bugfixes**3839- For file-like objects that are not seeked to the very beginning, we now40 send the content length for the number of bytes we will actually read, rather41 than the total size of the file, allowing partial file uploads.42- When uploading file-like objects, if they are empty or have no obvious43 content length we set ``Transfer-Encoding: chunked`` rather than44 ``Content-Length: 0``.45- We correctly receive the response in buffered mode when uploading chunked46 bodies.47- We now handle being passed a query string as a bytestring on Python 3, by48 decoding it as UTF-8.49- Sessions are now closed in all cases (exceptional and not) when using the50 functional API rather than leaking and waiting for the garbage collector to51 clean them up.52- Correctly handle digest auth headers with a malformed ``qop`` directive that53 contains no token, by treating it the same as if no ``qop`` directive was54 provided at all.55- Minor performance improvements when removing specific cookies by name.5657**Miscellaneous**5859- Updated urllib3 to 1.13.60612.8.1 (2015-10-13)62++++++++++++++++++6364**Bugfixes**
31 unmodified lines
9697- The ``json`` parameter to ``post()`` and friends will now only be used if98 neither ``data`` nor ``files`` are present, consistent with the99 documentation.53- We now ignore empty fields in the ``NO_PROXY`` enviroment variable.100- We now ignore empty fields in the ``NO_PROXY`` environment variable.101- Fixed problem where ``httplib.BadStatusLine`` would get raised if combining102 ``stream=True`` with ``contextlib.closing``.103- Prevented bugs where we would attempt to return the same connection back to104 the connection pool twice when sending a Chunked body.
474 unmodified lines
579580- Improved mime-compatible JSON handling581- Proxy fixes582- Path hack fixes536- Case-Insensistive Content-Encoding headers583- Case-Insensitive Content-Encoding headers584- Support for CJK parameters in form posts5855865870.14.1 (2012-10-01)
78 unmodified lines
6660.13.0 (2012-05-29)667+++++++++++++++++++668669- Removal of Requests.async in favor of `grequests <https://github.com/kennethreitz/grequests>`_623- Allow disabling of cookie persistiance.670- Allow disabling of cookie persistence.671- New implementation of safe_mode672- cookies.get now supports default argument673- Session cookies not saved when Session.request is called with return_response=False674- Env: no_proxy support.
463 unmodified lines
modified:LICENSE+1 added-1 removed
1Copyright 2015 Kenneth Reitz1Copyright 2016 Kenneth Reitz23 Licensed under the Apache License, Version 2.0 (the "License");4 you may not use this file except in compliance with the License.5 You may obtain a copy of the License at
8 unmodified lines
modified:Makefile+4 added-3 removed
4 unmodified lines
56test:7 # This runs all of the tests. To run an individual test, run py.test with8 # the -k flag, like "py.test -k test_path_is_not_double_encoded"9 py.test test_requests.py9 py.test tests1011coverage:12 py.test --verbose --cov-report term --cov=requests test_requests.py12 py.test --verbose --cov-report term --cov=requests tests1314ci: init15 py.test --junitxml=junit.xml16
10 unmodified lines
2728publish:29 python setup.py register30 python setup.py sdist upload31 python setup.py bdist_wheel upload31 python setup.py bdist_wheel --universal upload 32 rm -fr build dist .egg requests.egg-info333435docs-init:36 pip install -r docs/requirements.txt
4 unmodified lines
modified:README.rst+38 added-27 removed
5 unmodified lines
67.. image:: https://img.shields.io/pypi/dm/requests.svg8 :target: https://pypi.python.org/pypi/requests910Requests is the only *Non-GMO* HTTP library for Python, safe for human11consumption.1213**Warning:** Recreational use of other HTTP libraries may result in dangerous side-effects,14including: security vulnerabilities, verbose code, reinventing the wheel,15constantly reading documentation, depression, headaches, or even death.1617Behold, the power of Requests:1813Requests is an Apache2 Licensed HTTP library, written in Python, for human14beings.1516Most existing Python modules for sending HTTP requests are extremely17verbose and cumbersome. Python's builtin urllib2 module provides most of18the HTTP capabilities you should need, but the api is thoroughly broken.19It requires an enormous amount of work (even method overrides) to20perform the simplest of tasks.2122Things shouldn't be this way. Not in Python.2319.. code-block:: python2026 >>> r = requests.get('https://api.github.com', auth=('user', 'pass'))21 >>> r = requests.get('https://api.github.com/user', auth=('user', 'pass'))22 >>> r.status_code28 20423 20024 >>> r.headers['content-type']30 'application/json'25 'application/json; charset=utf8'26 >>> r.encoding27 'utf-8'28 >>> r.text32 ...29 u'{"type":"User"...'30 >>> r.json()31 {u'disk_usage': 368627, u'private_gists': 484, ...}3234See `the same code, without Requests <https://gist.github.com/973705>`_.33See `the similar code, sans Requests <https://gist.github.com/973705>`_.3436Requests allow you to send HTTP/1.1 requests. You can add headers, form data,37multipart files, and parameters with simple Python dictionaries, and access the38response data in the same way. It's powered by httplib and `urllib339<https://github.com/shazow/urllib3>`_, but it does all the hard work and crazy40hacks for you.35Requests allows you to send *organic, grass-fed* HTTP/1.1 requests, without the36need for manual labor. There's no need to manually add query strings to your37URLs, or to form-encode your POST data. Keep-alive and HTTP connection pooling38are 100% automatic, powered by `urllib3 <https://github.com/shazow/urllib3>`_,39which is embedded within Requests.4041Besides, all the cool kids are doing it. Requests is one of the most42downloaded Python packages of all time, pulling in over 7,000,000 downloads43every month. You don't want to be left out!4443Features44--------45Feature Support46---------------4748Requests is ready for today's web.4950- International Domains and URLs51- Keep-Alive & Connection Pooling52- Sessions with Cookie Persistence53- Browser-style SSL Verification54- Basic/Digest Authentication55- Elegant Key/Value Cookies56- Automatic Decompression57- Automatic Content Decoding58- Unicode Response Bodies59- Multipart File Uploads60- HTTP(S) Proxy Support61- Connection Timeouts62- Streaming Downloads63- ``.netrc`` Support64- Chunked Requests65- Thread-safety57- HTTP(S) proxy support6667Requests supports Python 2.6 — 3.5, and runs great on PyPy.6869Installation70------------71
1 unmodified line
7374.. code-block:: bash7576 $ pip install requests77 ✨🍰✨7879Satisfaction, guaranteed.8081Documentation82-------------8373Documentation is available at http://docs.python-requests.org/.84Fantastic documentation is available at http://docs.python-requests.org/, for a limited time only.858676Contribute77----------87How to Contribute88-----------------8990#. Check for open issues or open a fresh issue to start a discussion around a feature idea or a bug. There is a `Contributor Friendly`_ tag for issues that should be ideal for people who are not very familiar with the codebase yet.91#. Fork `the repository`_ on GitHub to start making your changes to the **master** branch (or branch off of it).92#. Write a test which shows that the bug was fixed or that the feature works as expected.
5 unmodified lines
added:requirements-to-freeze.txt+4 added
1pytest2pytest-cov3pytest-httpbin4sphinx
modified:requirements.txt+22 added-6 removed
1py==1.4.302pytest==2.8.13pytest-cov==2.1.04pytest-httpbin==0.0.75httpbin==0.4.06wheel1alabaster==0.7.72Babel==2.2.03coverage==4.0.34decorator==4.0.95docutils==0.126Flask==0.10.17httpbin==0.4.18itsdangerous==0.249Jinja2==2.810MarkupSafe==0.2311py==1.4.3112Pygments==2.1.113pytest==2.8.714pytest-cov==2.2.115pytest-httpbin==0.2.016pytz==2015.717six==1.10.018snowballstemmer==1.2.119Sphinx==1.3.520sphinx-rtd-theme==0.1.921Werkzeug==0.11.422wheel==0.29.0
deleted:setup.cfg-2 removed
1[wheel]2universal = 1
modified:setup.py+28 added-5 removed
4 unmodified lines
5import sys67from codecs import open89try:10 from setuptools import setup11except ImportError:12 from distutils.core import setup9from setuptools import setup10from setuptools.command.test import test as TestCommand111213class PyTest(TestCommand):14 user_options = [('pytest-args=', 'a', "Arguments to pass into py.test")]1516 def initialize_options(self):17 TestCommand.initialize_options(self)18 self.pytest_args = []1920 def finalize_options(self):21 TestCommand.finalize_options(self)22 self.test_args = []23 self.test_suite = True2425 def run_tests(self):26 import pytest2728 errno = pytest.main(self.pytest_args)29 sys.exit(errno)303132if sys.argv[-1] == 'publish':33 os.system('python setup.py sdist upload')34 sys.exit()35
8 unmodified lines
44 'requests.packages.urllib3.packages.ssl_match_hostname',45]4647requires = []48test_requirements = ['pytest>=2.8.0', 'pytest-httpbin==0.0.7', 'pytest-cov']4931version = ''50with open('requests/__init__.py', 'r') as fd:51 version = re.search(r'^__version__\s*=\s*[\'"]([^\'"]*)[\'"]',52 fd.read(), re.MULTILINE).group(1)53
25 unmodified lines
79 'Intended Audience :: Developers',80 'Natural Language :: English',81 'License :: OSI Approved :: Apache Software License',82 'Programming Language :: Python',83 'Programming Language :: Python :: 2.6',84 'Programming Language :: Python :: 2.7',85 'Programming Language :: Python :: 3',86 'Programming Language :: Python :: 3.3',87 'Programming Language :: Python :: 3.4',88 'Programming Language :: Python :: 3.5',89 'Programming Language :: Python :: Implementation :: CPython',90 'Programming Language :: Python :: Implementation :: PyPy'91 ),92 cmdclass={'test': PyTest},93 tests_require=test_requirements,94 extras_require={95 'security': ['pyOpenSSL>=0.13', 'ndg-httpsclient', 'pyasn1'],96 },97)
deleted:test_requests.py-1878 removed
1#!/usr/bin/env python2# -*- coding: utf-8 -*-34"""Tests for Requests."""56from __future__ import division7import json8import os9import pickle10import unittest11import collections12import contextlib1314import io15import requests16import pytest17from requests.adapters import HTTPAdapter18from requests.auth import HTTPDigestAuth, _basic_auth_str19from requests.compat import (20 Morsel, cookielib, getproxies, str, urljoin, urlparse, is_py3,21 builtin_str, OrderedDict22 )23from requests.cookies import cookiejar_from_dict, morsel_to_cookie24from requests.exceptions import (ConnectionError, ConnectTimeout,25 InvalidSchema, InvalidURL, MissingSchema,26 ReadTimeout, Timeout, RetryError)27from requests.models import PreparedRequest28from requests.structures import CaseInsensitiveDict29from requests.sessions import SessionRedirectMixin30from requests.models import urlencode31from requests.hooks import default_hooks32from testserver.server import Server33import socket34import threading35import time3637try:38 import StringIO39except ImportError:40 import io as StringIO4142try:43 from multiprocessing.pool import ThreadPool44except ImportError:45 ThreadPool = None4647if is_py3:48 def u(s):49 return s50else:51 def u(s):52 return s.decode('unicode-escape')535455@pytest.fixture56def httpbin(httpbin):57 # Issue #1483: Make sure the URL always has a trailing slash58 httpbin_url = httpbin.url.rstrip('/') + '/'5960 def inner(*suffix):61 return urljoin(httpbin_url, '/'.join(suffix))6263 return inner646566@pytest.fixture67def httpsbin_url(httpbin_secure):68 # Issue #1483: Make sure the URL always has a trailing slash69 httpbin_url = httpbin_secure.url.rstrip('/') + '/'7071 def inner(*suffix):72 return urljoin(httpbin_url, '/'.join(suffix))7374 return inner757677# Requests to this URL should always fail with a connection timeout (nothing78# listening on that port)79TARPIT = "http://10.255.255.1"8081class TestRequests(object):8283 _multiprocess_can_split_ = True8485 def setUp(self):86 """Create simple data set with headers."""87 pass8889 def tearDown(self):90 """Teardown."""91 pass9293 def test_entry_points(self):9495 requests.session96 requests.session().get97 requests.session().head98 requests.get99 requests.head100 requests.put101 requests.patch102 requests.post103104 def test_invalid_url(self):105 with pytest.raises(MissingSchema):106 requests.get('hiwpefhipowhefopw')107 with pytest.raises(InvalidSchema):108 requests.get('localhost:3128')109 with pytest.raises(InvalidSchema):110 requests.get('localhost.localdomain:3128/')111 with pytest.raises(InvalidSchema):112 requests.get('10.122.1.1:3128/')113 with pytest.raises(InvalidURL):114 requests.get('http://')115116 def test_basic_building(self):117 req = requests.Request()118 req.url = 'http://kennethreitz.org/'119 req.data = {'life': '42'}120121 pr = req.prepare()122 assert pr.url == req.url123 assert pr.body == 'life=42'124125 def test_no_content_length(self, httpbin):126 get_req = requests.Request('GET', httpbin('get')).prepare()127 assert 'Content-Length' not in get_req.headers128 head_req = requests.Request('HEAD', httpbin('head')).prepare()129 assert 'Content-Length' not in head_req.headers130131 def test_override_content_length(self, httpbin):132 headers = {133 'Content-Length': 'not zero'134 }135 r = requests.Request('POST', httpbin('post'), headers=headers).prepare()136 assert 'Content-Length' in r.headers137 assert r.headers['Content-Length'] == 'not zero'138139 def test_path_is_not_double_encoded(self):140 request = requests.Request('GET', "http://0.0.0.0/get/test case").prepare()141142 assert request.path_url == '/get/test%20case'143144 def test_params_are_added_before_fragment(self):145 request = requests.Request('GET',146 "http://example.com/path#fragment", params={"a": "b"}).prepare()147 assert request.url == "http://example.com/path?a=b#fragment"148 request = requests.Request('GET',149 "http://example.com/path?key=value#fragment", params={"a": "b"}).prepare()150 assert request.url == "http://example.com/path?key=value&a=b#fragment"151152 def test_params_original_order_is_preserved_by_default(self):153 param_ordered_dict = OrderedDict((('z', 1), ('a', 1), ('k', 1), ('d', 1)))154 session = requests.Session()155 request = requests.Request('GET', 'http://example.com/', params=param_ordered_dict)156 prep = session.prepare_request(request)157 assert prep.url == 'http://example.com/?z=1&a=1&k=1&d=1'158159 def test_params_bytes_are_encoded(self):160 request = requests.Request('GET', 'http://example.com',161 params=b'test=foo').prepare()162 assert request.url == 'http://example.com/?test=foo'163164 def test_mixed_case_scheme_acceptable(self, httpbin):165 s = requests.Session()166 s.proxies = getproxies()167 parts = urlparse(httpbin('get'))168 schemes = ['http://', 'HTTP://', 'hTTp://', 'HttP://']169 for scheme in schemes:170 url = scheme + parts.netloc + parts.path171 r = requests.Request('GET', url)172 r = s.send(r.prepare())173 assert r.status_code == 200, 'failed for scheme {0}'.format(scheme)174175 def test_HTTP_200_OK_GET_ALTERNATIVE(self, httpbin):176 r = requests.Request('GET', httpbin('get'))177 s = requests.Session()178 s.proxies = getproxies()179180 r = s.send(r.prepare())181182 assert r.status_code == 200183184 def test_HTTP_302_ALLOW_REDIRECT_GET(self, httpbin):185 r = requests.get(httpbin('redirect', '1'))186 assert r.status_code == 200187 assert r.history[0].status_code == 302188 assert r.history[0].is_redirect189190 # def test_HTTP_302_ALLOW_REDIRECT_POST(self):191 # r = requests.post(httpbin('status', '302'), data={'some': 'data'})192 # self.assertEqual(r.status_code, 200)193194 def test_HTTP_200_OK_GET_WITH_PARAMS(self, httpbin):195 heads = {'User-agent': 'Mozilla/5.0'}196197 r = requests.get(httpbin('user-agent'), headers=heads)198199 assert heads['User-agent'] in r.text200 assert r.status_code == 200201202 def test_HTTP_200_OK_GET_WITH_MIXED_PARAMS(self, httpbin):203 heads = {'User-agent': 'Mozilla/5.0'}204205 r = requests.get(httpbin('get') + '?test=true', params={'q': 'test'}, headers=heads)206 assert r.status_code == 200207208 def test_set_cookie_on_301(self, httpbin):209 s = requests.session()210 url = httpbin('cookies/set?foo=bar')211 s.get(url)212 assert s.cookies['foo'] == 'bar'213214 def test_cookie_sent_on_redirect(self, httpbin):215 s = requests.session()216 s.get(httpbin('cookies/set?foo=bar'))217 r = s.get(httpbin('redirect/1')) # redirects to httpbin('get')218 assert 'Cookie' in r.json()['headers']219220 def test_cookie_removed_on_expire(self, httpbin):221 s = requests.session()222 s.get(httpbin('cookies/set?foo=bar'))223 assert s.cookies['foo'] == 'bar'224 s.get(225 httpbin('response-headers'),226 params={227 'Set-Cookie':228 'foo=deleted; expires=Thu, 01-Jan-1970 00:00:01 GMT'229 }230 )231 assert 'foo' not in s.cookies232233 def test_cookie_quote_wrapped(self, httpbin):234 s = requests.session()235 s.get(httpbin('cookies/set?foo="bar:baz"'))236 assert s.cookies['foo'] == '"bar:baz"'237238 def test_cookie_persists_via_api(self, httpbin):239 s = requests.session()240 r = s.get(httpbin('redirect/1'), cookies={'foo': 'bar'})241 assert 'foo' in r.request.headers['Cookie']242 assert 'foo' in r.history[0].request.headers['Cookie']243244 def test_request_cookie_overrides_session_cookie(self, httpbin):245 s = requests.session()246 s.cookies['foo'] = 'bar'247 r = s.get(httpbin('cookies'), cookies={'foo': 'baz'})248 assert r.json()['cookies']['foo'] == 'baz'249 # Session cookie should not be modified250 assert s.cookies['foo'] == 'bar'251252 def test_request_cookies_not_persisted(self, httpbin):253 s = requests.session()254 s.get(httpbin('cookies'), cookies={'foo': 'baz'})255 # Sending a request with cookies should not add cookies to the session256 assert not s.cookies257258 def test_generic_cookiejar_works(self, httpbin):259 cj = cookielib.CookieJar()260 cookiejar_from_dict({'foo': 'bar'}, cj)261 s = requests.session()262 s.cookies = cj263 r = s.get(httpbin('cookies'))264 # Make sure the cookie was sent265 assert r.json()['cookies']['foo'] == 'bar'266 # Make sure the session cj is still the custom one267 assert s.cookies is cj268269 def test_param_cookiejar_works(self, httpbin):270 cj = cookielib.CookieJar()271 cookiejar_from_dict({'foo': 'bar'}, cj)272 s = requests.session()273 r = s.get(httpbin('cookies'), cookies=cj)274 # Make sure the cookie was sent275 assert r.json()['cookies']['foo'] == 'bar'276277 def test_requests_in_history_are_not_overridden(self, httpbin):278 resp = requests.get(httpbin('redirect/3'))279 urls = [r.url for r in resp.history]280 req_urls = [r.request.url for r in resp.history]281 assert urls == req_urls282283 def test_history_is_always_a_list(self, httpbin):284 """285 Show that even with redirects, Response.history is always a list.286 """287 resp = requests.get(httpbin('get'))288 assert isinstance(resp.history, list)289 resp = requests.get(httpbin('redirect/1'))290 assert isinstance(resp.history, list)291 assert not isinstance(resp.history, tuple)292293 def test_headers_on_session_with_None_are_not_sent(self, httpbin):294 """Do not send headers in Session.headers with None values."""295 ses = requests.Session()296 ses.headers['Accept-Encoding'] = None297 req = requests.Request('GET', httpbin('get'))298 prep = ses.prepare_request(req)299 assert 'Accept-Encoding' not in prep.headers300301 def test_user_agent_transfers(self, httpbin):302303 heads = {304 'User-agent': 'Mozilla/5.0 (github.com/kennethreitz/requests)'305 }306307 r = requests.get(httpbin('user-agent'), headers=heads)308 assert heads['User-agent'] in r.text309310 heads = {311 'user-agent': 'Mozilla/5.0 (github.com/kennethreitz/requests)'312 }313314 r = requests.get(httpbin('user-agent'), headers=heads)315 assert heads['user-agent'] in r.text316317 def test_HTTP_200_OK_HEAD(self, httpbin):318 r = requests.head(httpbin('get'))319 assert r.status_code == 200320321 def test_HTTP_200_OK_PUT(self, httpbin):322 r = requests.put(httpbin('put'))323 assert r.status_code == 200324325 def test_BASICAUTH_TUPLE_HTTP_200_OK_GET(self, httpbin):326 auth = ('user', 'pass')327 url = httpbin('basic-auth', 'user', 'pass')328329 r = requests.get(url, auth=auth)330 assert r.status_code == 200331332 r = requests.get(url)333 assert r.status_code == 401334335 s = requests.session()336 s.auth = auth337 r = s.get(url)338 assert r.status_code == 200339340 def test_connection_error_invalid_domain(self):341 """Connecting to an unknown domain should raise a ConnectionError"""342 with pytest.raises(ConnectionError):343 requests.get("http://doesnotexist.google.com")344345 def test_connection_error_invalid_port(self):346 """Connecting to an invalid port should raise a ConnectionError"""347 with pytest.raises(ConnectionError):348 requests.get("http://localhost:1", timeout=1)349350 def test_LocationParseError(self):351 """Inputing a URL that cannot be parsed should raise an InvalidURL error"""352 with pytest.raises(InvalidURL):353 requests.get("http://fe80::5054:ff:fe5a:fc0")354355 def test_basicauth_with_netrc(self, httpbin):356 auth = ('user', 'pass')357 wrong_auth = ('wronguser', 'wrongpass')358 url = httpbin('basic-auth', 'user', 'pass')359360 old_auth = requests.sessions.get_netrc_auth361362 try:363 def get_netrc_auth_mock(url):364 return auth365 requests.sessions.get_netrc_auth = get_netrc_auth_mock366367 # Should use netrc and work.368 r = requests.get(url)369 assert r.status_code == 200370371 # Given auth should override and fail.372 r = requests.get(url, auth=wrong_auth)373 assert r.status_code == 401374375 s = requests.session()376377 # Should use netrc and work.378 r = s.get(url)379 assert r.status_code == 200380381 # Given auth should override and fail.382 s.auth = wrong_auth383 r = s.get(url)384 assert r.status_code == 401385 finally:386 requests.sessions.get_netrc_auth = old_auth387388 def test_DIGEST_HTTP_200_OK_GET(self, httpbin):389390 auth = HTTPDigestAuth('user', 'pass')391 url = httpbin('digest-auth', 'auth', 'user', 'pass')392393 r = requests.get(url, auth=auth)394 assert r.status_code == 200395396 r = requests.get(url)397 assert r.status_code == 401398399 s = requests.session()400 s.auth = HTTPDigestAuth('user', 'pass')401 r = s.get(url)402 assert r.status_code == 200403404 def test_DIGEST_AUTH_RETURNS_COOKIE(self, httpbin):405 url = httpbin('digest-auth', 'auth', 'user', 'pass')406 auth = HTTPDigestAuth('user', 'pass')407 r = requests.get(url)408 assert r.cookies['fake'] == 'fake_value'409410 r = requests.get(url, auth=auth)411 assert r.status_code == 200412413 def test_DIGEST_AUTH_SETS_SESSION_COOKIES(self, httpbin):414 url = httpbin('digest-auth', 'auth', 'user', 'pass')415 auth = HTTPDigestAuth('user', 'pass')416 s = requests.Session()417 s.get(url, auth=auth)418 assert s.cookies['fake'] == 'fake_value'419420 def test_DIGEST_STREAM(self, httpbin):421422 auth = HTTPDigestAuth('user', 'pass')423 url = httpbin('digest-auth', 'auth', 'user', 'pass')424425 r = requests.get(url, auth=auth, stream=True)426 assert r.raw.read() != b''427428 r = requests.get(url, auth=auth, stream=False)429 assert r.raw.read() == b''430431 def test_DIGESTAUTH_WRONG_HTTP_401_GET(self, httpbin):432433 auth = HTTPDigestAuth('user', 'wrongpass')434 url = httpbin('digest-auth', 'auth', 'user', 'pass')435436 r = requests.get(url, auth=auth)437 assert r.status_code == 401438439 r = requests.get(url)440 assert r.status_code == 401441442 s = requests.session()443 s.auth = auth444 r = s.get(url)445 assert r.status_code == 401446447 def test_DIGESTAUTH_QUOTES_QOP_VALUE(self, httpbin):448449 auth = HTTPDigestAuth('user', 'pass')450 url = httpbin('digest-auth', 'auth', 'user', 'pass')451452 r = requests.get(url, auth=auth)453 assert '"auth"' in r.request.headers['Authorization']454455 def test_POSTBIN_GET_POST_FILES(self, httpbin):456457 url = httpbin('post')458 post1 = requests.post(url).raise_for_status()459460 post1 = requests.post(url, data={'some': 'data'})461 assert post1.status_code == 200462463 with open('requirements.txt') as f:464 post2 = requests.post(url, files={'some': f})465 assert post2.status_code == 200466467 post4 = requests.post(url, data='[{"some": "json"}]')468 assert post4.status_code == 200469470 with pytest.raises(ValueError):471 requests.post(url, files=['bad file data'])472473 def test_POSTBIN_GET_POST_FILES_WITH_DATA(self, httpbin):474475 url = httpbin('post')476 post1 = requests.post(url).raise_for_status()477478 post1 = requests.post(url, data={'some': 'data'})479 assert post1.status_code == 200480481 with open('requirements.txt') as f:482 post2 = requests.post(url,483 data={'some': 'data'}, files={'some': f})484 assert post2.status_code == 200485486 post4 = requests.post(url, data='[{"some": "json"}]')487 assert post4.status_code == 200488489 with pytest.raises(ValueError):490 requests.post(url, files=['bad file data'])491492 def test_conflicting_post_params(self, httpbin):493 url = httpbin('post')494 with open('requirements.txt') as f:495 pytest.raises(ValueError, "requests.post(url, data='[{\"some\": \"data\"}]', files={'some': f})")496 pytest.raises(ValueError, "requests.post(url, data=u('[{\"some\": \"data\"}]'), files={'some': f})")497498 def test_request_ok_set(self, httpbin):499 r = requests.get(httpbin('status', '404'))500 assert not r.ok501502 def test_status_raising(self, httpbin):503 r = requests.get(httpbin('status', '404'))504 with pytest.raises(requests.exceptions.HTTPError):505 r.raise_for_status()506507 r = requests.get(httpbin('status', '500'))508 assert not r.ok509510 def test_decompress_gzip(self, httpbin):511 r = requests.get(httpbin('gzip'))512 r.content.decode('ascii')513514 def test_unicode_get(self, httpbin):515 url = httpbin('/get')516 requests.get(url, params={'foo': 'føø'})517 requests.get(url, params={'føø': 'føø'})518 requests.get(url, params={'føø': 'føø'})519 requests.get(url, params={'foo': 'foo'})520 requests.get(httpbin('ø'), params={'foo': 'foo'})521522 def test_unicode_header_name(self, httpbin):523 requests.put(524 httpbin('put'),525 headers={str('Content-Type'): 'application/octet-stream'},526 data='\xff') # compat.str is unicode.527528 def test_pyopenssl_redirect(self, httpsbin_url, httpbin_ca_bundle):529 requests.get(httpsbin_url('status', '301'), verify=httpbin_ca_bundle)530531 def test_urlencoded_get_query_multivalued_param(self, httpbin):532533 r = requests.get(httpbin('get'), params=dict(test=['foo', 'baz']))534 assert r.status_code == 200535 assert r.url == httpbin('get?test=foo&test=baz')536537 def test_different_encodings_dont_break_post(self, httpbin):538 r = requests.post(httpbin('post'),539 data={'stuff': json.dumps({'a': 123})},540 params={'blah': 'asdf1234'},541 files={'file': ('test_requests.py', open(__file__, 'rb'))})542 assert r.status_code == 200543544 def test_unicode_multipart_post(self, httpbin):545 r = requests.post(httpbin('post'),546 data={'stuff': u('ëlïxr')},547 files={'file': ('test_requests.py', open(__file__, 'rb'))})548 assert r.status_code == 200549550 r = requests.post(httpbin('post'),551 data={'stuff': u('ëlïxr').encode('utf-8')},552 files={'file': ('test_requests.py', open(__file__, 'rb'))})553 assert r.status_code == 200554555 r = requests.post(httpbin('post'),556 data={'stuff': 'elixr'},557 files={'file': ('test_requests.py', open(__file__, 'rb'))})558 assert r.status_code == 200559560 r = requests.post(httpbin('post'),561 data={'stuff': 'elixr'.encode('utf-8')},562 files={'file': ('test_requests.py', open(__file__, 'rb'))})563 assert r.status_code == 200564565 def test_unicode_multipart_post_fieldnames(self, httpbin):566 filename = os.path.splitext(__file__)[0] + '.py'567 r = requests.Request(method='POST',568 url=httpbin('post'),569 data={'stuff'.encode('utf-8'): 'elixr'},570 files={'file': ('test_requests.py',571 open(filename, 'rb'))})572 prep = r.prepare()573 assert b'name="stuff"' in prep.body574 assert b'name="b\'stuff\'"' not in prep.body575576 def test_unicode_method_name(self, httpbin):577 files = {'file': open('test_requests.py', 'rb')}578 r = requests.request(579 method=u('POST'), url=httpbin('post'), files=files)580 assert r.status_code == 200581582 def test_unicode_method_name_with_request_object(self, httpbin):583 files = {'file': open('test_requests.py', 'rb')}584 s = requests.Session()585 req = requests.Request(u("POST"), httpbin('post'), files=files)586 prep = s.prepare_request(req)587 assert isinstance(prep.method, builtin_str)588 assert prep.method == "POST"589590 resp = s.send(prep)591 assert resp.status_code == 200592593 def test_custom_content_type(self, httpbin):594 r = requests.post(595 httpbin('post'),596 data={'stuff': json.dumps({'a': 123})},597 files={'file1': ('test_requests.py', open(__file__, 'rb')),598 'file2': ('test_requests', open(__file__, 'rb'),599 'text/py-content-type')})600 assert r.status_code == 200601 assert b"text/py-content-type" in r.request.body602603 def test_hook_receives_request_arguments(self, httpbin):604 def hook(resp, **kwargs):605 assert resp is not None606 assert kwargs != {}607608 requests.Request('GET', httpbin(), hooks={'response': hook})609610 def test_session_hooks_are_used_with_no_request_hooks(self, httpbin):611 hook = lambda x, *args, **kwargs: x612 s = requests.Session()613 s.hooks['response'].append(hook)614 r = requests.Request('GET', httpbin())615 prep = s.prepare_request(r)616 assert prep.hooks['response'] != []617 assert prep.hooks['response'] == [hook]618619 def test_session_hooks_are_overriden_by_request_hooks(self, httpbin):620 hook1 = lambda x, *args, **kwargs: x621 hook2 = lambda x, *args, **kwargs: x622 assert hook1 is not hook2623 s = requests.Session()624 s.hooks['response'].append(hook2)625 r = requests.Request('GET', httpbin(), hooks={'response': [hook1]})626 prep = s.prepare_request(r)627 assert prep.hooks['response'] == [hook1]628629 def test_prepared_request_hook(self, httpbin):630 def hook(resp, **kwargs):631 resp.hook_working = True632 return resp633634 req = requests.Request('GET', httpbin(), hooks={'response': hook})635 prep = req.prepare()636637 s = requests.Session()638 s.proxies = getproxies()639 resp = s.send(prep)640641 assert hasattr(resp, 'hook_working')642643 def test_prepared_from_session(self, httpbin):644 class DummyAuth(requests.auth.AuthBase):645 def __call__(self, r):646 r.headers['Dummy-Auth-Test'] = 'dummy-auth-test-ok'647 return r648649 req = requests.Request('GET', httpbin('headers'))650 assert not req.auth651652 s = requests.Session()653 s.auth = DummyAuth()654655 prep = s.prepare_request(req)656 resp = s.send(prep)657658 assert resp.json()['headers'][659 'Dummy-Auth-Test'] == 'dummy-auth-test-ok'660661 def test_prepare_request_with_bytestring_url(self):662 req = requests.Request('GET', b'https://httpbin.org/')663 s = requests.Session()664 prep = s.prepare_request(req)665 assert prep.url == "https://httpbin.org/"666667 def test_links(self):668 r = requests.Response()669 r.headers = {670 'cache-control': 'public, max-age=60, s-maxage=60',671 'connection': 'keep-alive',672 'content-encoding': 'gzip',673 'content-type': 'application/json; charset=utf-8',674 'date': 'Sat, 26 Jan 2013 16:47:56 GMT',675 'etag': '"6ff6a73c0e446c1f61614769e3ceb778"',676 'last-modified': 'Sat, 26 Jan 2013 16:22:39 GMT',677 'link': ('<https://api.github.com/users/kennethreitz/repos?'678 'page=2&per_page=10>; rel="next", <https://api.github.'679 'com/users/kennethreitz/repos?page=7&per_page=10>; '680 ' rel="last"'),681 'server': 'GitHub.com',682 'status': '200 OK',683 'vary': 'Accept',684 'x-content-type-options': 'nosniff',685 'x-github-media-type': 'github.beta',686 'x-ratelimit-limit': '60',687 'x-ratelimit-remaining': '57'688 }689 assert r.links['next']['rel'] == 'next'690691 def test_cookie_parameters(self):692 key = 'some_cookie'693 value = 'some_value'694 secure = True695 domain = 'test.com'696 rest = {'HttpOnly': True}697698 jar = requests.cookies.RequestsCookieJar()699 jar.set(key, value, secure=secure, domain=domain, rest=rest)700701 assert len(jar) == 1702 assert 'some_cookie' in jar703704 cookie = list(jar)[0]705 assert cookie.secure == secure706 assert cookie.domain == domain707 assert cookie._rest['HttpOnly'] == rest['HttpOnly']708709 def test_cookie_as_dict_keeps_len(self):710 key = 'some_cookie'711 value = 'some_value'712713 key1 = 'some_cookie1'714 value1 = 'some_value1'715716 jar = requests.cookies.RequestsCookieJar()717 jar.set(key, value)718 jar.set(key1, value1)719720 d1 = dict(jar)721 d2 = dict(jar.iteritems())722 d3 = dict(jar.items())723724 assert len(jar) == 2725 assert len(d1) == 2726 assert len(d2) == 2727 assert len(d3) == 2728729 def test_cookie_as_dict_keeps_items(self):730 key = 'some_cookie'731 value = 'some_value'732733 key1 = 'some_cookie1'734 value1 = 'some_value1'735736 jar = requests.cookies.RequestsCookieJar()737 jar.set(key, value)738 jar.set(key1, value1)739740 d1 = dict(jar)741 d2 = dict(jar.iteritems())742 d3 = dict(jar.items())743744 assert d1['some_cookie'] == 'some_value'745 assert d2['some_cookie'] == 'some_value'746 assert d3['some_cookie1'] == 'some_value1'747748 def test_cookie_as_dict_keys(self):749 key = 'some_cookie'750 value = 'some_value'751752 key1 = 'some_cookie1'753 value1 = 'some_value1'754755 jar = requests.cookies.RequestsCookieJar()756 jar.set(key, value)757 jar.set(key1, value1)758759 keys = jar.keys()760 assert keys == list(keys)761 # make sure one can use keys multiple times762 assert list(keys) == list(keys)763764 def test_cookie_as_dict_values(self):765 key = 'some_cookie'766 value = 'some_value'767768 key1 = 'some_cookie1'769 value1 = 'some_value1'770771 jar = requests.cookies.RequestsCookieJar()772 jar.set(key, value)773 jar.set(key1, value1)774775 values = jar.values()776 assert values == list(values)777 # make sure one can use values multiple times778 assert list(values) == list(values)779780 def test_cookie_as_dict_items(self):781 key = 'some_cookie'782 value = 'some_value'783784 key1 = 'some_cookie1'785 value1 = 'some_value1'786787 jar = requests.cookies.RequestsCookieJar()788 jar.set(key, value)789 jar.set(key1, value1)790791 items = jar.items()792 assert items == list(items)793 # make sure one can use items multiple times794 assert list(items) == list(items)795796 def test_time_elapsed_blank(self, httpbin):797 r = requests.get(httpbin('get'))798 td = r.elapsed799 total_seconds = ((td.microseconds + (td.seconds + td.days * 24 * 3600)800 * 10**6) / 10**6)801 assert total_seconds > 0.0802803 def test_response_is_iterable(self):804 r = requests.Response()805 io = StringIO.StringIO('abc')806 read_ = io.read807808 def read_mock(amt, decode_content=None):809 return read_(amt)810 setattr(io, 'read', read_mock)811 r.raw = io812 assert next(iter(r))813 io.close()814815 def test_response_decode_unicode(self):816 """817 When called with decode_unicode, Response.iter_content should always818 return unicode.819 """820 r = requests.Response()821 r._content_consumed = True822 r._content = b'the content'823 r.encoding = 'ascii'824825 chunks = r.iter_content(decode_unicode=True)826 assert all(isinstance(chunk, str) for chunk in chunks)827828 # also for streaming829 r = requests.Response()830 r.raw = io.BytesIO(b'the content')831 r.encoding = 'ascii'832 chunks = r.iter_content(decode_unicode=True)833 assert all(isinstance(chunk, str) for chunk in chunks)834835 def test_request_and_response_are_pickleable(self, httpbin):836 r = requests.get(httpbin('get'))837838 # verify we can pickle the original request839 assert pickle.loads(pickle.dumps(r.request))840841 # verify we can pickle the response and that we have access to842 # the original request.843 pr = pickle.loads(pickle.dumps(r))844 assert r.request.url == pr.request.url845 assert r.request.headers == pr.request.headers846847 def test_get_auth_from_url(self):848 url = 'http://user:pass@complex.url.com/path?query=yes'849 assert ('user', 'pass') == requests.utils.get_auth_from_url(url)850851 def test_get_auth_from_url_encoded_spaces(self):852 url = 'http://user:pass%20pass@complex.url.com/path?query=yes'853 assert ('user', 'pass pass') == requests.utils.get_auth_from_url(url)854855 def test_get_auth_from_url_not_encoded_spaces(self):856 url = 'http://user:pass pass@complex.url.com/path?query=yes'857 assert ('user', 'pass pass') == requests.utils.get_auth_from_url(url)858859 def test_get_auth_from_url_percent_chars(self):860 url = 'http://user%25user:pass@complex.url.com/path?query=yes'861 assert ('user%user', 'pass') == requests.utils.get_auth_from_url(url)862863 def test_get_auth_from_url_encoded_hashes(self):864 url = 'http://user:pass%23pass@complex.url.com/path?query=yes'865 assert ('user', 'pass#pass') == requests.utils.get_auth_from_url(url)866867 def test_cannot_send_unprepared_requests(self, httpbin):868 r = requests.Request(url=httpbin())869 with pytest.raises(ValueError):870 requests.Session().send(r)871872 def test_http_error(self):873 error = requests.exceptions.HTTPError()874 assert not error.response875 response = requests.Response()876 error = requests.exceptions.HTTPError(response=response)877 assert error.response == response878 error = requests.exceptions.HTTPError('message', response=response)879 assert str(error) == 'message'880 assert error.response == response881882 def test_session_pickling(self, httpbin):883 r = requests.Request('GET', httpbin('get'))884 s = requests.Session()885886 s = pickle.loads(pickle.dumps(s))887 s.proxies = getproxies()888889 r = s.send(r.prepare())890 assert r.status_code == 200891892 def test_fixes_1329(self, httpbin):893 """894 Ensure that header updates are done case-insensitively.895 """896 s = requests.Session()897 s.headers.update({'ACCEPT': 'BOGUS'})898 s.headers.update({'accept': 'application/json'})899 r = s.get(httpbin('get'))900 headers = r.request.headers901 assert headers['accept'] == 'application/json'902 assert headers['Accept'] == 'application/json'903 assert headers['ACCEPT'] == 'application/json'904905 def test_uppercase_scheme_redirect(self, httpbin):906 parts = urlparse(httpbin('html'))907 url = "HTTP://" + parts.netloc + parts.path908 r = requests.get(httpbin('redirect-to'), params={'url': url})909 assert r.status_code == 200910 assert r.url.lower() == url.lower()911912 def test_transport_adapter_ordering(self):913 s = requests.Session()914 order = ['https://', 'http://']915 assert order == list(s.adapters)916 s.mount('http://git', HTTPAdapter())917 s.mount('http://github', HTTPAdapter())918 s.mount('http://github.com', HTTPAdapter())919 s.mount('http://github.com/about/', HTTPAdapter())920 order = [921 'http://github.com/about/',922 'http://github.com',923 'http://github',924 'http://git',925 'https://',926 'http://',927 ]928 assert order == list(s.adapters)929 s.mount('http://gittip', HTTPAdapter())930 s.mount('http://gittip.com', HTTPAdapter())931 s.mount('http://gittip.com/about/', HTTPAdapter())932 order = [933 'http://github.com/about/',934 'http://gittip.com/about/',935 'http://github.com',936 'http://gittip.com',937 'http://github',938 'http://gittip',939 'http://git',940 'https://',941 'http://',942 ]943 assert order == list(s.adapters)944 s2 = requests.Session()945 s2.adapters = {'http://': HTTPAdapter()}946 s2.mount('https://', HTTPAdapter())947 assert 'http://' in s2.adapters948 assert 'https://' in s2.adapters949950 def test_header_remove_is_case_insensitive(self, httpbin):951 # From issue #1321952 s = requests.Session()953 s.headers['foo'] = 'bar'954 r = s.get(httpbin('get'), headers={'FOO': None})955 assert 'foo' not in r.request.headers956957 def test_params_are_merged_case_sensitive(self, httpbin):958 s = requests.Session()959 s.params['foo'] = 'bar'960 r = s.get(httpbin('get'), params={'FOO': 'bar'})961 assert r.json()['args'] == {'foo': 'bar', 'FOO': 'bar'}962963 def test_long_authinfo_in_url(self):964 url = 'http://{0}:{1}@{2}:9000/path?query#frag'.format(965 'E8A3BE87-9E3F-4620-8858-95478E385B5B',966 'EA770032-DA4D-4D84-8CE9-29C6D910BF1E',967 'exactly-------------sixty-----------three------------characters',968 )969 r = requests.Request('GET', url).prepare()970 assert r.url == url971972 def test_header_keys_are_native(self, httpbin):973 headers = {u('unicode'): 'blah', 'byte'.encode('ascii'): 'blah'}974 r = requests.Request('GET', httpbin('get'), headers=headers)975 p = r.prepare()976977 # This is testing that they are builtin strings. A bit weird, but there978 # we go.979 assert 'unicode' in p.headers.keys()980 assert 'byte' in p.headers.keys()981982 def test_can_send_nonstring_objects_with_files(self, httpbin):983 data = {'a': 0.0}984 files = {'b': 'foo'}985 r = requests.Request('POST', httpbin('post'), data=data, files=files)986 p = r.prepare()987988 assert 'multipart/form-data' in p.headers['Content-Type']989990 def test_can_send_bytes_bytearray_objects_with_files(self, httpbin):991 # Test bytes:992 data = {'a': 'this is a string'}993 files = {'b': b'foo'}994 r = requests.Request('POST', httpbin('post'), data=data, files=files)995 p = r.prepare()996 assert 'multipart/form-data' in p.headers['Content-Type']997 # Test bytearrays:998 files = {'b': bytearray(b'foo')}999 r = requests.Request('POST', httpbin('post'), data=data, files=files)1000 p = r.prepare()1001 assert 'multipart/form-data' in p.headers['Content-Type']10021003 def test_can_send_file_object_with_non_string_filename(self, httpbin):1004 f = io.BytesIO()1005 f.name = 21006 r = requests.Request('POST', httpbin('post'), files={'f': f})1007 p = r.prepare()10081009 assert 'multipart/form-data' in p.headers['Content-Type']10101011 def test_autoset_header_values_are_native(self, httpbin):1012 data = 'this is a string'1013 length = '16'1014 req = requests.Request('POST', httpbin('post'), data=data)1015 p = req.prepare()10161017 assert p.headers['Content-Length'] == length10181019 def test_nonhttp_schemes_dont_check_URLs(self):1020 test_urls = (1021 'data:image/gif;base64,R0lGODlhAQABAHAAACH5BAUAAAAALAAAAAABAAEAAAICRAEAOw==',1022 'file:///etc/passwd',1023 'magnet:?xt=urn:btih:be08f00302bc2d1d3cfa3af02024fa647a271431',1024 )1025 for test_url in test_urls:1026 req = requests.Request('GET', test_url)1027 preq = req.prepare()1028 assert test_url == preq.url10291030 def test_auth_is_stripped_on_redirect_off_host(self, httpbin):1031 r = requests.get(1032 httpbin('redirect-to'),1033 params={'url': 'http://www.google.co.uk'},1034 auth=('user', 'pass'),1035 )1036 assert r.history[0].request.headers['Authorization']1037 assert not r.request.headers.get('Authorization', '')10381039 def test_auth_is_retained_for_redirect_on_host(self, httpbin):1040 r = requests.get(httpbin('redirect/1'), auth=('user', 'pass'))1041 h1 = r.history[0].request.headers['Authorization']1042 h2 = r.request.headers['Authorization']10431044 assert h1 == h210451046 def test_manual_redirect_with_partial_body_read(self, httpbin):1047 s = requests.Session()1048 r1 = s.get(httpbin('redirect/2'), allow_redirects=False, stream=True)1049 assert r1.is_redirect1050 rg = s.resolve_redirects(r1, r1.request, stream=True)10511052 # read only the first eight bytes of the response body,1053 # then follow the redirect1054 r1.iter_content(8)1055 r2 = next(rg)1056 assert r2.is_redirect10571058 # read all of the response via iter_content,1059 # then follow the redirect1060 for _ in r2.iter_content():1061 pass1062 r3 = next(rg)1063 assert not r3.is_redirect10641065 def _patch_adapter_gzipped_redirect(self, session, url):1066 adapter = session.get_adapter(url=url)1067 org_build_response = adapter.build_response1068 self._patched_response = False10691070 def build_response(*args, **kwargs):1071 resp = org_build_response(*args, **kwargs)1072 if not self._patched_response:1073 resp.raw.headers['content-encoding'] = 'gzip'1074 self._patched_response = True1075 return resp10761077 adapter.build_response = build_response10781079 def test_redirect_with_wrong_gzipped_header(self, httpbin):1080 s = requests.Session()1081 url = httpbin('redirect/1')1082 self._patch_adapter_gzipped_redirect(s, url)1083 s.get(url)10841085 def test_basic_auth_str_is_always_native(self):1086 s = _basic_auth_str("test", "test")1087 assert isinstance(s, builtin_str)1088 assert s == "Basic dGVzdDp0ZXN0"10891090 def test_requests_history_is_saved(self, httpbin):1091 r = requests.get(httpbin('redirect/5'))1092 total = r.history[-1].history1093 i = 01094 for item in r.history:1095 assert item.history == total[0:i]1096 i = i + 110971098 def test_json_param_post_content_type_works(self, httpbin):1099 r = requests.post(1100 httpbin('post'),1101 json={'life': 42}1102 )1103 assert r.status_code == 2001104 assert 'application/json' in r.request.headers['Content-Type']1105 assert {'life': 42} == r.json()['json']11061107 def test_json_param_post_should_not_override_data_param(self, httpbin):1108 r = requests.Request(method='POST', url=httpbin('post'),1109 data={'stuff': 'elixr'},1110 json={'music': 'flute'})1111 prep = r.prepare()1112 assert 'stuff=elixr' == prep.body11131114 def test_response_iter_lines(self, httpbin):1115 r = requests.get(httpbin('stream/4'), stream=True)1116 assert r.status_code == 20011171118 it = r.iter_lines()1119 next(it)1120 assert len(list(it)) == 311211122 def test_unconsumed_session_response_closes_connection(self, httpbin):1123 s = requests.session()11241125 with contextlib.closing(s.get(httpbin('stream/4'), stream=True)) as response:1126 pass11271128 assert response._content_consumed is False1129 assert response.raw.closed11301131 @pytest.mark.xfail1132 def test_response_iter_lines_reentrant(self, httpbin):1133 """Response.iter_lines() is not reentrant safe"""1134 r = requests.get(httpbin('stream/4'), stream=True)1135 assert r.status_code == 20011361137 next(r.iter_lines())1138 assert len(list(r.iter_lines())) == 3113911401141class TestContentEncodingDetection(unittest.TestCase):11421143 def test_none(self):1144 encodings = requests.utils.get_encodings_from_content('')1145 assert not len(encodings)11461147 def test_html_charset(self):1148 """HTML5 meta charset attribute"""1149 content = '<meta charset="UTF-8">'1150 encodings = requests.utils.get_encodings_from_content(content)1151 assert len(encodings) == 11152 assert encodings[0] == 'UTF-8'11531154 def test_html4_pragma(self):1155 """HTML4 pragma directive"""1156 content = '<meta http-equiv="Content-type" content="text/html;charset=UTF-8">'1157 encodings = requests.utils.get_encodings_from_content(content)1158 assert len(encodings) == 11159 assert encodings[0] == 'UTF-8'11601161 def test_xhtml_pragma(self):1162 """XHTML 1.x served with text/html MIME type"""1163 content = '<meta http-equiv="Content-type" content="text/html;charset=UTF-8" />'1164 encodings = requests.utils.get_encodings_from_content(content)1165 assert len(encodings) == 11166 assert encodings[0] == 'UTF-8'11671168 def test_xml(self):1169 """XHTML 1.x served as XML"""1170 content = '<?xml version="1.0" encoding="UTF-8"?>'1171 encodings = requests.utils.get_encodings_from_content(content)1172 assert len(encodings) == 11173 assert encodings[0] == 'UTF-8'11741175 def test_precedence(self):1176 content = '''1177 <?xml version="1.0" encoding="XML"?>1178 <meta charset="HTML5">1179 <meta http-equiv="Content-type" content="text/html;charset=HTML4" />1180 '''.strip()1181 encodings = requests.utils.get_encodings_from_content(content)1182 assert encodings == ['HTML5', 'HTML4', 'XML']11831184 def test_chunked_upload(self):1185 """can safely send generators"""1186 block_server = threading.Event()1187 server = Server.basic_response_server(wait_to_close_event=block_server)1188 data = (i for i in [b'a', b'b', b'c']) 11891190 with server as (host, port):1191 url = 'http://{}:{}/'.format(host, port)1192 r = requests.post(url, data=data, stream=True)1193 block_server.set() # release server block11941195 assert r.status_code == 2001196 assert r.request.headers['Transfer-Encoding'] == 'chunked'11971198class TestCaseInsensitiveDict(unittest.TestCase):11991200 def test_mapping_init(self):1201 cid = CaseInsensitiveDict({'Foo': 'foo', 'BAr': 'bar'})1202 assert len(cid) == 21203 assert 'foo' in cid1204 assert 'bar' in cid12051206 def test_iterable_init(self):1207 cid = CaseInsensitiveDict([('Foo', 'foo'), ('BAr', 'bar')])1208 assert len(cid) == 21209 assert 'foo' in cid1210 assert 'bar' in cid12111212 def test_kwargs_init(self):1213 cid = CaseInsensitiveDict(FOO='foo', BAr='bar')1214 assert len(cid) == 21215 assert 'foo' in cid1216 assert 'bar' in cid12171218 def test_docstring_example(self):1219 cid = CaseInsensitiveDict()1220 cid['Accept'] = 'application/json'1221 assert cid['aCCEPT'] == 'application/json'1222 assert list(cid) == ['Accept']12231224 def test_len(self):1225 cid = CaseInsensitiveDict({'a': 'a', 'b': 'b'})1226 cid['A'] = 'a'1227 assert len(cid) == 212281229 def test_getitem(self):1230 cid = CaseInsensitiveDict({'Spam': 'blueval'})1231 assert cid['spam'] == 'blueval'1232 assert cid['SPAM'] == 'blueval'12331234 def test_fixes_649(self):1235 """__setitem__ should behave case-insensitively."""1236 cid = CaseInsensitiveDict()1237 cid['spam'] = 'oneval'1238 cid['Spam'] = 'twoval'1239 cid['sPAM'] = 'redval'1240 cid['SPAM'] = 'blueval'1241 assert cid['spam'] == 'blueval'1242 assert cid['SPAM'] == 'blueval'1243 assert list(cid.keys()) == ['SPAM']12441245 def test_delitem(self):1246 cid = CaseInsensitiveDict()1247 cid['Spam'] = 'someval'1248 del cid['sPam']1249 assert 'spam' not in cid1250 assert len(cid) == 012511252 def test_contains(self):1253 cid = CaseInsensitiveDict()1254 cid['Spam'] = 'someval'1255 assert 'Spam' in cid1256 assert 'spam' in cid1257 assert 'SPAM' in cid1258 assert 'sPam' in cid1259 assert 'notspam' not in cid12601261 def test_get(self):1262 cid = CaseInsensitiveDict()1263 cid['spam'] = 'oneval'1264 cid['SPAM'] = 'blueval'1265 assert cid.get('spam') == 'blueval'1266 assert cid.get('SPAM') == 'blueval'1267 assert cid.get('sPam') == 'blueval'1268 assert cid.get('notspam', 'default') == 'default'12691270 def test_update(self):1271 cid = CaseInsensitiveDict()1272 cid['spam'] = 'blueval'1273 cid.update({'sPam': 'notblueval'})1274 assert cid['spam'] == 'notblueval'1275 cid = CaseInsensitiveDict({'Foo': 'foo', 'BAr': 'bar'})1276 cid.update({'fOO': 'anotherfoo', 'bAR': 'anotherbar'})1277 assert len(cid) == 21278 assert cid['foo'] == 'anotherfoo'1279 assert cid['bar'] == 'anotherbar'12801281 def test_update_retains_unchanged(self):1282 cid = CaseInsensitiveDict({'foo': 'foo', 'bar': 'bar'})1283 cid.update({'foo': 'newfoo'})1284 assert cid['bar'] == 'bar'12851286 def test_iter(self):1287 cid = CaseInsensitiveDict({'Spam': 'spam', 'Eggs': 'eggs'})1288 keys = frozenset(['Spam', 'Eggs'])1289 assert frozenset(iter(cid)) == keys12901291 def test_equality(self):1292 cid = CaseInsensitiveDict({'SPAM': 'blueval', 'Eggs': 'redval'})1293 othercid = CaseInsensitiveDict({'spam': 'blueval', 'eggs': 'redval'})1294 assert cid == othercid1295 del othercid['spam']1296 assert cid != othercid1297 assert cid == {'spam': 'blueval', 'eggs': 'redval'}1298 assert cid != object()12991300 def test_setdefault(self):1301 cid = CaseInsensitiveDict({'Spam': 'blueval'})1302 assert cid.setdefault('spam', 'notblueval') == 'blueval'1303 assert cid.setdefault('notspam', 'notblueval') == 'notblueval'13041305 def test_lower_items(self):1306 cid = CaseInsensitiveDict({1307 'Accept': 'application/json',1308 'user-Agent': 'requests',1309 })1310 keyset = frozenset(lowerkey for lowerkey, v in cid.lower_items())1311 lowerkeyset = frozenset(['accept', 'user-agent'])1312 assert keyset == lowerkeyset13131314 def test_preserve_key_case(self):1315 cid = CaseInsensitiveDict({1316 'Accept': 'application/json',1317 'user-Agent': 'requests',1318 })1319 keyset = frozenset(['Accept', 'user-Agent'])1320 assert frozenset(i[0] for i in cid.items()) == keyset1321 assert frozenset(cid.keys()) == keyset1322 assert frozenset(cid) == keyset13231324 def test_preserve_last_key_case(self):1325 cid = CaseInsensitiveDict({1326 'Accept': 'application/json',1327 'user-Agent': 'requests',1328 })1329 cid.update({'ACCEPT': 'application/json'})1330 cid['USER-AGENT'] = 'requests'1331 keyset = frozenset(['ACCEPT', 'USER-AGENT'])1332 assert frozenset(i[0] for i in cid.items()) == keyset1333 assert frozenset(cid.keys()) == keyset1334 assert frozenset(cid) == keyset13351336 def test_copy(self):1337 cid = CaseInsensitiveDict({1338 'Accept': 'application/json',1339 'user-Agent': 'requests',1340 })1341 cid_copy = cid.copy()1342 assert cid == cid_copy1343 cid['changed'] = True1344 assert cid != cid_copy134513461347class UtilsTestCase(unittest.TestCase):13481349 def test_super_len_io_streams(self):1350 """ Ensures that we properly deal with different kinds of IO streams. """1351 # uses StringIO or io.StringIO (see import above)1352 from io import BytesIO1353 from requests.utils import super_len13541355 assert super_len(StringIO.StringIO()) == 01356 assert super_len(1357 StringIO.StringIO('with so much drama in the LBC')) == 2913581359 assert super_len(BytesIO()) == 01360 assert super_len(1361 BytesIO(b"it's kinda hard bein' snoop d-o-double-g")) == 4013621363 try:1364 import cStringIO1365 except ImportError:1366 pass1367 else:1368 assert super_len(1369 cStringIO.StringIO('but some how, some way...')) == 2513701371 def test_super_len_correctly_calculates_len_of_partially_read_file(self):1372 """Ensure that we handle partially consumed file like objects."""1373 from requests.utils import super_len1374 s = StringIO.StringIO()1375 s.write('foobarbogus')1376 assert super_len(s) == 013771378 def test_get_environ_proxies_ip_ranges(self):1379 """Ensures that IP addresses are correctly matches with ranges1380 in no_proxy variable."""1381 from requests.utils import get_environ_proxies1382 os.environ['no_proxy'] = "192.168.0.0/24,127.0.0.1,localhost.localdomain,172.16.1.1"1383 assert get_environ_proxies('http://192.168.0.1:5000/') == {}1384 assert get_environ_proxies('http://192.168.0.1/') == {}1385 assert get_environ_proxies('http://172.16.1.1/') == {}1386 assert get_environ_proxies('http://172.16.1.1:5000/') == {}1387 assert get_environ_proxies('http://192.168.1.1:5000/') != {}1388 assert get_environ_proxies('http://192.168.1.1/') != {}13891390 def test_get_environ_proxies(self):1391 """Ensures that IP addresses are correctly matches with ranges1392 in no_proxy variable."""1393 from requests.utils import get_environ_proxies1394 os.environ['no_proxy'] = "127.0.0.1,localhost.localdomain,192.168.0.0/24,172.16.1.1"1395 assert get_environ_proxies(1396 'http://localhost.localdomain:5000/v1.0/') == {}1397 assert get_environ_proxies('http://www.requests.com/') != {}13981399 def test_select_proxies(self):1400 """Make sure we can select per-host proxies correctly."""1401 from requests.utils import select_proxy1402 proxies = {'http': 'http://http.proxy',1403 'http://some.host': 'http://some.host.proxy'}1404 assert select_proxy('hTTp://u:p@Some.Host/path', proxies) == 'http://some.host.proxy'1405 assert select_proxy('hTTp://u:p@Other.Host/path', proxies) == 'http://http.proxy'1406 assert select_proxy('hTTps://Other.Host', proxies) is None14071408 def test_guess_filename_when_int(self):1409 from requests.utils import guess_filename1410 assert None is guess_filename(1)14111412 def test_guess_filename_when_filename_is_an_int(self):1413 from requests.utils import guess_filename1414 fake = type('Fake', (object,), {'name': 1})()1415 assert None is guess_filename(fake)14161417 def test_guess_filename_with_file_like_obj(self):1418 from requests.utils import guess_filename1419 from requests import compat1420 fake = type('Fake', (object,), {'name': b'value'})()1421 guessed_name = guess_filename(fake)1422 assert b'value' == guessed_name1423 assert isinstance(guessed_name, compat.bytes)14241425 def test_guess_filename_with_unicode_name(self):1426 from requests.utils import guess_filename1427 from requests import compat1428 filename = b'value'.decode('utf-8')1429 fake = type('Fake', (object,), {'name': filename})()1430 guessed_name = guess_filename(fake)1431 assert filename == guessed_name1432 assert isinstance(guessed_name, compat.str)14331434 def test_is_ipv4_address(self):1435 from requests.utils import is_ipv4_address1436 assert is_ipv4_address('8.8.8.8')1437 assert not is_ipv4_address('8.8.8.8.8')1438 assert not is_ipv4_address('localhost.localdomain')14391440 def test_is_valid_cidr(self):1441 from requests.utils import is_valid_cidr1442 assert not is_valid_cidr('8.8.8.8')1443 assert is_valid_cidr('192.168.1.0/24')14441445 def test_dotted_netmask(self):1446 from requests.utils import dotted_netmask1447 assert dotted_netmask(8) == '255.0.0.0'1448 assert dotted_netmask(24) == '255.255.255.0'1449 assert dotted_netmask(25) == '255.255.255.128'14501451 def test_address_in_network(self):1452 from requests.utils import address_in_network1453 assert address_in_network('192.168.1.1', '192.168.1.0/24')1454 assert not address_in_network('172.16.0.1', '192.168.1.0/24')14551456 def test_get_auth_from_url(self):1457 """Ensures that username and password in well-encoded URI as per1458 RFC 3986 are correclty extracted."""1459 from requests.utils import get_auth_from_url1460 from requests.compat import quote1461 percent_encoding_test_chars = "%!*'();:@&=+$,/?#[] "1462 url_address = "request.com/url.html#test"1463 url = "http://" + quote(1464 percent_encoding_test_chars, '') + ':' + quote(1465 percent_encoding_test_chars, '') + '@' + url_address1466 (username, password) = get_auth_from_url(url)1467 assert username == percent_encoding_test_chars1468 assert password == percent_encoding_test_chars14691470 def test_requote_uri_with_unquoted_percents(self):1471 """Ensure we handle unquoted percent signs in redirects.14721473 See: https://github.com/kennethreitz/requests/issues/23561474 """1475 from requests.utils import requote_uri1476 bad_uri = 'http://example.com/fiz?buz=%ppicture'1477 quoted = 'http://example.com/fiz?buz=%25ppicture'1478 assert quoted == requote_uri(bad_uri)14791480 def test_requote_uri_properly_requotes(self):1481 """Ensure requoting doesn't break expectations."""1482 from requests.utils import requote_uri1483 quoted = 'http://example.com/fiz?buz=%25ppicture'1484 assert quoted == requote_uri(quoted)148514861487class TestMorselToCookieExpires(unittest.TestCase):14881489 """Tests for morsel_to_cookie when morsel contains expires."""14901491 def test_expires_valid_str(self):1492 """Test case where we convert expires from string time."""14931494 morsel = Morsel()1495 morsel['expires'] = 'Thu, 01-Jan-1970 00:00:01 GMT'1496 cookie = morsel_to_cookie(morsel)1497 assert cookie.expires == 114981499 def test_expires_invalid_int(self):1500 """Test case where an invalid type is passed for expires."""15011502 morsel = Morsel()1503 morsel['expires'] = 1001504 with pytest.raises(TypeError):1505 morsel_to_cookie(morsel)15061507 def test_expires_invalid_str(self):1508 """Test case where an invalid string is input."""15091510 morsel = Morsel()1511 morsel['expires'] = 'woops'1512 with pytest.raises(ValueError):1513 morsel_to_cookie(morsel)15141515 def test_expires_none(self):1516 """Test case where expires is None."""15171518 morsel = Morsel()1519 morsel['expires'] = None1520 cookie = morsel_to_cookie(morsel)1521 assert cookie.expires is None152215231524class TestMorselToCookieMaxAge(unittest.TestCase):15251526 """Tests for morsel_to_cookie when morsel contains max-age."""15271528 def test_max_age_valid_int(self):1529 """Test case where a valid max age in seconds is passed."""15301531 morsel = Morsel()1532 morsel['max-age'] = 601533 cookie = morsel_to_cookie(morsel)1534 assert isinstance(cookie.expires, int)15351536 def test_max_age_invalid_str(self):1537 """Test case where a invalid max age is passed."""15381539 morsel = Morsel()1540 morsel['max-age'] = 'woops'1541 with pytest.raises(TypeError):1542 morsel_to_cookie(morsel)154315441545class TestTimeout:1546 def test_stream_timeout(self, httpbin):1547 try:1548 requests.get(httpbin('delay/10'), timeout=2.0)1549 except requests.exceptions.Timeout as e:1550 assert 'Read timed out' in e.args[0].args[0]15511552 def test_invalid_timeout(self, httpbin):1553 with pytest.raises(ValueError) as e:1554 requests.get(httpbin('get'), timeout=(3, 4, 5))1555 assert '(connect, read)' in str(e)15561557 with pytest.raises(ValueError) as e:1558 requests.get(httpbin('get'), timeout="foo")1559 assert 'must be an int or float' in str(e)15601561 def test_none_timeout(self, httpbin):1562 """ Check that you can set None as a valid timeout value.15631564 To actually test this behavior, we'd want to check that setting the1565 timeout to None actually lets the request block past the system default1566 timeout. However, this would make the test suite unbearably slow.1567 Instead we verify that setting the timeout to None does not prevent the1568 request from succeeding.1569 """1570 r = requests.get(httpbin('get'), timeout=None)1571 assert r.status_code == 20015721573 def test_read_timeout(self, httpbin):1574 try:1575 requests.get(httpbin('delay/10'), timeout=(None, 0.1))1576 assert False, "The recv() request should time out."1577 except ReadTimeout:1578 pass15791580 def test_connect_timeout(self):1581 try:1582 requests.get(TARPIT, timeout=(0.1, None))1583 assert False, "The connect() request should time out."1584 except ConnectTimeout as e:1585 assert isinstance(e, ConnectionError)1586 assert isinstance(e, Timeout)15871588 def test_total_timeout_connect(self):1589 try:1590 requests.get(TARPIT, timeout=(0.1, 0.1))1591 assert False, "The connect() request should time out."1592 except ConnectTimeout:1593 pass15941595 def test_encoded_methods(self, httpbin):1596 """See: https://github.com/kennethreitz/requests/issues/2316"""1597 r = requests.request(b'GET', httpbin('get'))1598 assert r.ok159916001601SendCall = collections.namedtuple('SendCall', ('args', 'kwargs'))160216031604class RedirectSession(SessionRedirectMixin):1605 def __init__(self, order_of_redirects):1606 self.redirects = order_of_redirects1607 self.calls = []1608 self.max_redirects = 301609 self.cookies = {}1610 self.trust_env = False16111612 def send(self, *args, **kwargs):1613 self.calls.append(SendCall(args, kwargs))1614 return self.build_response()16151616 def build_response(self):1617 request = self.calls[-1].args[0]1618 r = requests.Response()16191620 try:1621 r.status_code = int(self.redirects.pop(0))1622 except IndexError:1623 r.status_code = 20016241625 r.headers = CaseInsensitiveDict({'Location': '/'})1626 r.raw = self._build_raw()1627 r.request = request1628 return r16291630 def _build_raw(self):1631 string = StringIO.StringIO('')1632 setattr(string, 'release_conn', lambda *args: args)1633 return string163416351636class TestRedirects:1637 default_keyword_args = {1638 'stream': False,1639 'verify': True,1640 'cert': None,1641 'timeout': None,1642 'allow_redirects': False,1643 'proxies': {},1644 }16451646 def test_requests_are_updated_each_time(self, httpbin):1647 session = RedirectSession([303, 307])1648 prep = requests.Request('POST', httpbin('post')).prepare()1649 r0 = session.send(prep)1650 assert r0.request.method == 'POST'1651 assert session.calls[-1] == SendCall((r0.request,), {})1652 redirect_generator = session.resolve_redirects(r0, prep)1653 for response in redirect_generator:1654 assert response.request.method == 'GET'1655 send_call = SendCall((response.request,),1656 TestRedirects.default_keyword_args)1657 assert session.calls[-1] == send_call1658165916601661@pytest.fixture1662def list_of_tuples():1663 return [1664 (('a', 'b'), ('c', 'd')),1665 (('c', 'd'), ('a', 'b')),1666 (('a', 'b'), ('c', 'd'), ('e', 'f')),1667 ]166816691670def test_data_argument_accepts_tuples(list_of_tuples):1671 """1672 Ensure that the data argument will accept tuples of strings1673 and properly encode them.1674 """1675 for data in list_of_tuples:1676 p = PreparedRequest()1677 p.prepare(1678 method='GET',1679 url='http://www.example.com',1680 data=data,1681 hooks=default_hooks()1682 )1683 assert p.body == urlencode(data)168416851686def assert_copy(p, p_copy):1687 for attr in ('method', 'url', 'headers', '_cookies', 'body', 'hooks'):1688 assert getattr(p, attr) == getattr(p_copy, attr)168916901691def test_prepared_request_empty_copy():1692 p = PreparedRequest()1693 assert_copy(p, p.copy())169416951696def test_prepared_request_no_cookies_copy():1697 p = PreparedRequest()1698 p.prepare(1699 method='GET',1700 url='http://www.example.com',1701 data='foo=bar',1702 hooks=default_hooks()1703 )1704 assert_copy(p, p.copy())170517061707def test_prepared_request_complete_copy():1708 p = PreparedRequest()1709 p.prepare(1710 method='GET',1711 url='http://www.example.com',1712 data='foo=bar',1713 hooks=default_hooks(),1714 cookies={'foo': 'bar'}1715 )1716 assert_copy(p, p.copy())171717181719def test_prepare_unicode_url():1720 p = PreparedRequest()1721 p.prepare(1722 method='GET',1723 url=u('http://www.example.com/üniçø∂é'),1724 )1725 assert_copy(p, p.copy())172617271728def test_urllib3_retries(httpbin):1729 from requests.packages.urllib3.util import Retry1730 s = requests.Session()1731 s.mount('http://', HTTPAdapter(max_retries=Retry(1732 total=2, status_forcelist=[500]1733 )))17341735 with pytest.raises(RetryError):1736 s.get(httpbin('status/500'))173717381739def test_urllib3_pool_connection_closed(httpbin):1740 s = requests.Session()1741 s.mount('http://', HTTPAdapter(pool_connections=0, pool_maxsize=0))17421743 try:1744 s.get(httpbin('status/200'))1745 except ConnectionError as e:1746 assert u"Pool is closed." in str(e)174717481749def test_vendor_aliases():1750 from requests.packages import urllib31751 from requests.packages import chardet17521753 with pytest.raises(ImportError):1754 from requests.packages import webbrowser17551756class TestTestServer(unittest.TestCase):1757 def test_basic(self):1758 question = b"sucess?"1759 answer = b"yeah, success"1760 def handler(sock):1761 text = sock.recv(1000)1762 assert text == question 1763 sock.send(answer)1764 1765 with Server(handler) as (host, port):1766 sock = socket.socket()1767 sock.connect((host, port))1768 sock.send(question)1769 text = sock.recv(1000)1770 assert text == answer1771 sock.close()17721773 def test_server_closes(self):1774 with Server.basic_response_server() as (host, port):1775 sock = socket.socket()1776 sock.connect((host, port))17771778 sock.close()17791780 with pytest.raises(socket.error):1781 new_sock = socket.socket()1782 new_sock.connect((host, port))17831784 def test_text_response(self):1785 server = Server.text_response_server(1786 "HTTP/1.1 200 OK\r\n" + 1787 "Content-Length: 6\r\n" +1788 "\r\nroflol"1789 )17901791 with server as (host, port):1792 r = requests.get('http://{}:{}'.format(host, port))17931794 assert r.status_code == 2001795 assert r.text == 'roflol'1796 assert r.headers['Content-Length'] == '6' 1797 1798 def test_basic_response(self):1799 with Server.basic_response_server() as (host, port):1800 r = requests.get('http://{}:{}'.format(host, port))1801 assert r.status_code == 2001802 assert r.text == ''1803 assert r.headers['Content-Length'] == '0'18041805 def test_basic_waiting_server(self):1806 block_server = threading.Event()18071808 with Server.basic_response_server(wait_to_close_event=block_server) as (host, port):1809 sock = socket.socket()1810 sock.connect((host, port))1811 sock.send(b'send something')1812 time.sleep(2.5)1813 sock.send(b'still alive')1814 block_server.set() # release server block18151816 def test_multiple_requests(self):1817 requests_to_handle = 51818 1819 server = Server.basic_response_server(requests_to_handle=requests_to_handle)18201821 with server as (host, port):1822 server_url = 'http://{}:{}'.format(host, port)1823 for _ in range(requests_to_handle):1824 r = requests.get(server_url)1825 assert r.status_code == 20018261827 # the (n+1)th request fails1828 with pytest.raises(requests.exceptions.ConnectionError):1829 r = requests.get(server_url)18301831 def test_request_recovery(self):1832 server = Server.basic_response_server(requests_to_handle=2)1833 first_request = "put your hands up in the air"1834 second_request = "put your hand down in the floor"18351836 with server as address:1837 sock1 = socket.socket()1838 sock2 = socket.socket()1839 1840 sock1.connect(address)1841 sock1.send(first_request.encode())1842 sock1.close()18431844 sock2.connect(address)1845 sock2.send(second_request.encode())1846 sock2.close()18471848 assert server.handler_results[0] == first_request1849 assert server.handler_results[1] == second_request18501851 def test_requests_after_timeout_are_not_received(self):1852 server = Server.basic_response_server(request_timeout=1)18531854 with server as address:1855 sock = socket.socket()1856 sock.connect(address)1857 time.sleep(1.5)1858 sock.send(b"hehehe, not received")1859 sock.close()18601861 assert server.handler_results[0] == ""186218631864 def test_request_recovery_with_bigger_timeout(self):1865 server = Server.basic_response_server(request_timeout=3)1866 data = "bananadine"18671868 with server as address:1869 sock = socket.socket() 1870 sock.connect(address)1871 time.sleep(1.5)1872 sock.send(data.encode())1873 sock.close()1874 1875 assert server.handler_results[0] == data18761877if __name__ == '__main__':1878 unittest.main()