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
Provenance
- Commit
141db28- Tree
baefbba- Author
Braulio Valdivielso Martínez <brlvldvlsmrtnz@gmail.com>- Committer
Braulio Valdivielso Martínez <brlvldvlsmrtnz@gmail.com>- Parent 1
9ac5a6e- Parent 2
4618423
70 files changed+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+ */12+13+var 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+ }108+109+ typeof callback === "string" && konami.load(callback);110+ if (typeof callback === "function") {111+ konami.code = callback;112+ konami.load();113+ }114+115+ return konami;116+};added:docs/_templates/hacks.html+54 added
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354<!-- Alabaster (krTheme++) Hacks -->
<!-- CSS Adjustments (I'm very picky.) --><style type="text/css">
/* Rezzy requires precise alignment. */ img.logo {margin-left: -20px!important;}
/* "Quick Search" should be capitalized. */ div#searchbox h3 {text-transform: capitalize;}
/* Make the document a little wider, less code is cut-off. */ div.document {width: 1008px;}
/* Much-improved spacing around code blocks. */ div.highlight pre {padding: 11px 14px;}
/* Remain Responsive! */ @media screen and (max-width: 1008px) { div.sphinxsidebar {display: none;} div.document {width: 100%!important;}
/* Have code blocks escape the document right-margin. */ div.highlight pre {margin-right: -30px;} }
</style>
<!-- Analytics tracking for Kenneth. --><script type="text/javascript"> var _gauges = _gauges || []; (function() { var t = document.createElement('script'); t.type = 'text/javascript'; t.async = true; t.id = 'gauges-tracker'; t.setAttribute('data-site-id', '56ca7a57c88d9011080024dd'); t.setAttribute('data-track-path', 'https://track.gaug.es/track.gif'); t.src = 'https://d36ee2fcip1434.cloudfront.net/track.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(t, s); })();</script>
<!-- There are no more hacks. --><!-- இڿڰۣ-ڰۣ— --><!-- Love, Kenneth Reitz -->
<script src="{{ pathto('_static/', 1) }}/konami.js"></script><script> var easter_egg = new Konami('http://fortunes.herokuapp.com/random/raw');</script>
<!-- That was not a hack. That was art. -->No newline at end of filemodified:docs/_templates/sidebarintro.html+31 added-16 removed
12 unmodified lines1314151617181918192020212223242324252626272828292930313233343536373831323334353637383940414243443 unmodified lines4849505152535455565758596061626364656612 unmodified lines Requests is an elegant and simple HTTP library for Python, built for human beings.</p>
<h3>Stay Informed</h3><p>Receive updates on new releases and upcoming projects.</p>
<p> <a href="https://gumroad.com/l/RRZc" class="gumroad-button">Buy Requests Pro</a></p><p><iframe src="http://ghbtns.com/github-btn.html?user=kennethreitz&type=follow&count=false" allowtransparency="true" frameborder="0" scrolling="0" width="200" height="20"></iframe></p>
<p><a href="https://twitter.com/kennethreitz" class="twitter-follow-button" data-show-count="false">Follow @kennethreitz</a> <script>!function(d,s,id){var js,fjs=d.getElementsByTagName(s)[0],p=/^http:/.test(d.location)?'http':'https';if(!d.getElementById(id)){js=d.createElement(s);js.id=id;js.src=p+'://platform.twitter.com/widgets.js';fjs.parentNode.insertBefore(js,fjs);}}(document, 'script', 'twitter-wjs');</script></p>
<h3>Get Updates</h3><p>Receive updates on new releases and upcoming projects.</p><p><a href="http://tinyletter.com/kennethreitz">Join Mailing List</a>.</p>
<p><a href="http://tinyletter.com/kennethreitz">Subscribe to Newsletter</a></p><h3>Other Projects</h3>
<h3>Translations</h3><p>More <a href="http://kennethreitz.org/">Kenneth Reitz</a> projects:</p><ul><li><a href="http://docs.python-requests.org/">English</a></li><li><a href="http://fr.python-requests.org/">French</a></li><li><a href="http://de.python-requests.org/">German</a></li><li><a href="http://jp.python-requests.org/">Japanese</a></li><li><a href="http://cn.python-requests.org/">Chinese</a></li><li><a href="http://pt.python-requests.org/">Portuguese</a></li><li><a href="http://it.python-requests.org/">Italian</a></li><li><a href="http://es.python-requests.org/">Spanish</a></li> <li><a href="http://pep8.org/">pep8.org</a></li> <li><a href="http://httpbin.org/">httpbin.org</a></li> <li><a href="http://python-guide.org">The Python Guide</a></li> <li><a href="https://github.com/kennethreitz/records">Records: SQL for Humans</a></li> <li><a href="http://www.git-legit.org">Legit: Git for Humans</a></li> <li><a href="http://docs.python-tablib.org/en/latest/">Tablib: Tabular Datasets</a></li> <li><a href="http://markdownplease.com">Markdown, Please!</a></li></ul>
<h3>Useful Links</h3><ul> <li><a href="http://docs.python-requests.org/en/latest/community/recommended/">Recommended Packages and Extensions</a></li>
3 unmodified lines <li><a href="http://pypi.python.org/pypi/requests">Requests @ PyPI</a></li> <li><a href="http://github.com/kennethreitz/requests/issues">Issue Tracker</a></li> <li><a href="http://docs.python-requests.org/en/latest/community/updates/#software-updates">Release History</a></li></ul>
<h3>Translations</h3>
<ul> <li><a href="http://docs.python-requests.org/">English</a></li> <li><a href="http://fr.python-requests.org/">French</a></li> <li><a href="http://de.python-requests.org/">German</a></li> <li><a href="http://jp.python-requests.org/">Japanese</a></li> <li><a href="http://cn.python-requests.org/">Chinese</a></li> <li><a href="http://pt.python-requests.org/">Portuguese</a></li> <li><a href="http://it.python-requests.org/">Italian</a></li> <li><a href="http://es.python-requests.org/">Spanish</a></li></ul>
modified:docs/_templates/sidebarlogo.html+33 added-6 removed
12 unmodified lines131415161718192021171819242021222324252627282930313233343536373839404142434445464748495051525312 unmodified lines human beings. You are currently looking at the documentation of the development release.</p>
<p> <a href="https://gumroad.com/l/RRZc" class="gumroad-button">Buy Requests Pro</a></p>
<h3>Get Updates</h3><h3>Stay Informed</h3><p>Receive updates on new releases and upcoming projects.</p>
<p><a href="http://tinyletter.com/kennethreitz">Subscribe to Newsletter</a></p><p><a href="http://tinyletter.com/kennethreitz">Join Mailing List</a>.</p>
<p><iframe src="http://ghbtns.com/github-btn.html?user=kennethreitz&type=follow&count=false" allowtransparency="true" frameborder="0" scrolling="0" width="200" height="20"></iframe></p>
<p><a href="https://twitter.com/kennethreitz" class="twitter-follow-button" data-show-count="false">Follow @kennethreitz</a> <script>!function(d,s,id){var js,fjs=d.getElementsByTagName(s)[0],p=/^http:/.test(d.location)?'http':'https';if(!d.getElementById(id)){js=d.createElement(s);js.id=id;js.src=p+'://platform.twitter.com/widgets.js';fjs.parentNode.insertBefore(js,fjs);}}(document, 'script', 'twitter-wjs');</script></p>
<h3>Other Projects</h3>
<p>More <a href="http://kennethreitz.org/">Kenneth Reitz</a> projects:</p><ul> <li><a href="http://pep8.org/">pep8.org</a></li> <li><a href="http://httpbin.org/">httpbin.org</a></li> <li><a href="http://python-guide.org">The Python Guide</a></li> <li><a href="https://github.com/kennethreitz/records">Records: SQL for Humans</a></li> <li><a href="http://www.git-legit.org">Legit: Git for Humans</a></li> <li><a href="http://docs.python-tablib.org/en/latest/">Tablib: Tabular Datasets</a></li> <li><a href="http://markdownplease.com">Markdown, Please!</a></li></ul>
<h3>Translations</h3>
<ul> <li><a href="http://docs.python-requests.org/">English</a></li> <li><a href="http://fr.python-requests.org/">French</a></li> <li><a href="http://de.python-requests.org/">German</a></li> <li><a href="http://jp.python-requests.org/">Japanese</a></li> <li><a href="http://cn.python-requests.org/">Chinese</a></li> <li><a href="http://pt.python-requests.org/">Portuguese</a></li> <li><a href="http://it.python-requests.org/">Italian</a></li> <li><a href="http://es.python-requests.org/">Spanish</a></li></ul>
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- */8-9-{% set page_width = '940px' %}10-{% set sidebar_width = '220px' %}11-12-@import url("basic.css");13-14-/* -- page layout ----------------------------------------------------------- */15-16-body {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-}24-25-div.document {26- width: {{ page_width }};27- margin: 30px auto 0 auto;28-}29-30-div.documentwrapper {31- float: left;32- width: 100%;33-}34-35-div.bodywrapper {36- margin: 0 0 0 {{ sidebar_width }};37-}38-39-div.sphinxsidebar {40- width: {{ sidebar_width }};41-}42-43-hr {44- border: 1px solid #B1B4B6;45-}46-47-div.body {48- background-color: #ffffff;49- color: #3E4349;50- padding: 0 30px 0 30px;51-}52-53-img.floatingflask {54- padding: 0 0 10px 10px;55- float: right;56-}57-58-div.footer {59- width: {{ page_width }};60- margin: 20px auto 30px auto;61- font-size: 14px;62- color: #888;63- text-align: right;64-}65-66-div.footer a {67- color: #888;68-}69-70-div.related {71- display: none;72-}73-74-div.sphinxsidebar a {75- color: #444;76- text-decoration: none;77- border-bottom: 1px dotted #999;78-}79-80-div.sphinxsidebar a:hover {81- border-bottom: 1px solid #999;82-}83-84-div.sphinxsidebar {85- font-size: 14px;86- line-height: 1.5;87-}88-89-div.sphinxsidebarwrapper {90- padding: 18px 10px;91-}92-93-div.sphinxsidebarwrapper p.logo {94- padding: 0;95- margin: -10px 0 0 -20px;96- text-align: center;97-}98-99-div.sphinxsidebar h3,100-div.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-}108-109-div.sphinxsidebar h4 {110- font-size: 20px;111-}112-113-div.sphinxsidebar h3 a {114- color: #444;115-}116-117-div.sphinxsidebar p.logo a,118-div.sphinxsidebar h3 a,119-div.sphinxsidebar p.logo a:hover,120-div.sphinxsidebar h3 a:hover {121- border: none;122-}123-124-div.sphinxsidebar p {125- color: #555;126- margin: 10px 0;127-}128-129-div.sphinxsidebar ul {130- margin: 10px 0;131- padding: 0;132- color: #000;133-}134-135-div.sphinxsidebar input {136- border: 1px solid #ccc;137- font-family: 'Georgia', serif;138- font-size: 1em;139-}140-141-/* -- body styles ----------------------------------------------------------- */142-143-a {144- color: #004B6B;145- text-decoration: underline;146-}147-148-a:hover {149- color: #6D4100;150- text-decoration: underline;151-}152-153-div.body h1,154-div.body h2,155-div.body h3,156-div.body h4,157-div.body h5,158-div.body h6 {159- font-family: 'Garamond', 'Georgia', serif;160- font-weight: normal;161- margin: 30px 0px 10px 0px;162- padding: 0;163-}164-165-div.body h1 { margin-top: 0; padding-top: 0; font-size: 240%; }166-div.body h2 { font-size: 180%; }167-div.body h3 { font-size: 150%; }168-div.body h4 { font-size: 130%; }169-div.body h5 { font-size: 100%; }170-div.body h6 { font-size: 100%; }171-172-a.headerlink {173- color: #ddd;174- padding: 0 4px;175- text-decoration: none;176-}177-178-a.headerlink:hover {179- color: #444;180- background: #eaeaea;181-}182-183-div.body p, div.body dd, div.body li {184- line-height: 1.4em;185-}186-187-div.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-}194-195-div.admonition tt.xref, div.admonition a tt {196- border-bottom: 1px solid #fafafa;197-}198-199-dd div.admonition {200- margin-left: -60px;201- padding-left: 60px;202-}203-204-div.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-}212-213-div.admonition p.last {214- margin-bottom: 0;215-}216-217-div.highlight {218- background-color: white;219-}220-221-dt:target, .highlight {222- background: #FAF3E8;223-}224-225-div.note {226- background-color: #eee;227- border: 1px solid #ccc;228-}229-230-div.seealso {231- background-color: #ffc;232- border: 1px solid #ff6;233-}234-235-div.topic {236- background-color: #eee;237-}238-239-p.admonition-title {240- display: inline;241-}242-243-p.admonition-title:after {244- content: ":";245-}246-247-pre, tt {248- font-family: 'Consolas', 'Menlo', 'Deja Vu Sans Mono', 'Bitstream Vera Sans Mono', monospace;249- font-size: 0.9em;250-}251-252-img.screenshot {253-}254-255-tt.descname, tt.descclassname {256- font-size: 0.95em;257-}258-259-tt.descname {260- padding-right: 0.08em;261-}262-263-img.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-}268-269-table.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-}275-276-table.docutils td, table.docutils th {277- border: 1px solid #888;278- padding: 0.25em 0.7em;279-}280-281-table.field-list, table.footnote {282- border: none;283- -moz-box-shadow: none;284- -webkit-box-shadow: none;285- box-shadow: none;286-}287-288-table.footnote {289- margin: 15px 0;290- width: 100%;291- border: 1px solid #eee;292- background: #fdfdfd;293- font-size: 0.9em;294-}295-296-table.footnote + table.footnote {297- margin-top: -15px;298- border-top: none;299-}300-301-table.field-list th {302- padding: 0 0.8em 0 0;303-}304-305-table.field-list td {306- padding: 0;307-}308-309-table.footnote td.label {310- width: 0px;311- padding: 0.3em 0 0.3em 0.5em;312-}313-314-table.footnote td {315- padding: 0.3em 0.5em;316-}317-318-dl {319- margin: 0;320- padding: 0;321-}322-323-dl dd {324- margin-left: 30px;325-}326-327-blockquote {328- margin: 0 0 0 30px;329- padding: 0;330-}331-332-ul, ol {333- margin: 10px 0 10px 30px;334- padding: 0;335-}336-337-pre {338- background: #eee;339- padding: 7px 30px;340- margin: 15px -30px;341- line-height: 1.3em;342-}343-344-dl pre, blockquote pre, li pre {345- margin-left: -60px;346- padding-left: 60px;347-}348-349-dl dl pre {350- margin-left: -90px;351- padding-left: 90px;352-}353-354-tt {355- background-color: #ecf0f3;356- color: #222;357- /* padding: 1px 2px; */358-}359-360-tt.xref, a tt {361- background-color: #FBFBFB;362- border-bottom: 1px solid white;363-}364-365-a.reference {366- text-decoration: none;367- border-bottom: 1px dotted #004B6B;368-}369-370-a.reference:hover {371- border-bottom: 1px solid #6D4100;372-}373-374-a.footnote-reference {375- text-decoration: none;376- font-size: 0.7em;377- vertical-align: top;378- border-bottom: 1px dotted #004B6B;379-}380-381-a.footnote-reference:hover {382- border-bottom: 1px solid #6D4100;383-}384-385-a:hover tt {386- background: #EEE;387-}388-389-390-@media screen and (max-width: 870px) {391-392- div.sphinxsidebar {393- display: none;394- }395-396- div.document {397- width: 100%;398-399- }400-401- div.documentwrapper {402- margin-left: 0;403- margin-top: 0;404- margin-right: 0;405- margin-bottom: 0;406- }407-408- div.bodywrapper {409- margin-top: 0;410- margin-right: 0;411- margin-bottom: 0;412- margin-left: 0;413- }414-415- ul {416- margin-left: 0;417- }418-419- .document {420- width: auto;421- }422-423- .footer {424- width: auto;425- }426-427- .bodywrapper {428- margin: 0;429- }430-431- .footer {432- width: auto;433- }434-435- .github {436- display: none;437- }438-439-440-441-}442-443-444-445-@media screen and (max-width: 875px) {446-447- body {448- margin: 0;449- padding: 20px 30px;450- }451-452- div.documentwrapper {453- float: none;454- background: white;455- }456-457- 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- }466-467- div.sphinxsidebar h3, div.sphinxsidebar h4, div.sphinxsidebar p,468- div.sphinxsidebar h3 a {469- color: white;470- }471-472- div.sphinxsidebar a {473- color: #aaa;474- }475-476- div.sphinxsidebar p.logo {477- display: none;478- }479-480- div.document {481- width: 100%;482- margin: 0;483- }484-485- div.related {486- display: block;487- margin: 0;488- padding: 10px 0 20px 0;489- }490-491- div.related ul,492- div.related ul li {493- margin: 0;494- padding: 0;495- }496-497- div.footer {498- display: none;499- }500-501- div.bodywrapper {502- margin: 0;503- }504-505- div.body {506- min-height: 0;507- padding: 0;508- }509-510- .rtd_doc_footer {511- display: none;512- }513-514- .document {515- width: auto;516- }517-518- .footer {519- width: auto;520- }521-522- .footer {523- width: auto;524- }525-526- .github {527- display: none;528- }529-}530-531-532-/* misc. */533-534-.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- © 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>18-19- <script type="text/javascript" src="https://gumroad.com/js/gumroad.js"></script>20-21- <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>38-39- <script type="text/javascript">40- new HelloBar(36402,48802);41- </script>42-43-44- <script type="text/javascript">45-46- var _gaq = _gaq || [];47- _gaq.push(['_setAccount', 'UA-8742933-11']);48- _gaq.push(['_setDomainName', 'none']);49- _gaq.push(['_setAllowLinker', true]);50- _gaq.push(['_trackPageview']);51-52- (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- })();57-58- </script>59-60- <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>73-74- <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>83-84-85-{%- endblock %}deleted:docs/_themes/kr/relations.html-19 removed
12345678910111213141516171819<h3>Related Topics</h3><ul> <li><a href="{{ pathto(master_doc) }}">Documentation overview</a><ul> {%- for parent in parents %} <li><a href="{{ parent.link|e }}">{{ parent.title }}</a><ul> {%- endfor %} {%- if prev %} <li>Previous: <a href="{{ prev.link|e }}" title="{{ _('previous chapter') }}">{{ prev.title }}</a></li> {%- endif %} {%- if next %} <li>Next: <a href="{{ next.link|e }}" title="{{ _('next chapter') }}">{{ next.title }}</a></li> {%- endif %} {%- for parent in parents %} </ul></li> {%- endfor %} </ul></li></ul>deleted:docs/_themes/kr/theme.conf-7 removed
1-[theme]2-inherit = basic3-stylesheet = flasky.css4-pygments_style = flask_theme_support.FlaskyStyle5-6-[options]7-touch_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- */11-12-@import url("basic.css");13-14-/* -- page layout ----------------------------------------------------------- */15-16-body {17- font-family: 'Georgia', serif;18- font-size: 17px;19- color: #000;20- background: white;21- margin: 0;22- padding: 0;23-}24-25-div.documentwrapper {26- float: left;27- width: 100%;28-}29-30-div.bodywrapper {31- margin: 40px auto 0 auto;32- width: 700px;33-}34-35-hr {36- border: 1px solid #B1B4B6;37-}38-39-div.body {40- background-color: #ffffff;41- color: #3E4349;42- padding: 0 30px 30px 30px;43-}44-45-img.floatingflask {46- padding: 0 0 10px 10px;47- float: right;48-}49-50-div.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-}58-59-div.footer a {60- color: #888;61- text-decoration: underline;62-}63-64-div.related {65- line-height: 32px;66- color: #888;67-}68-69-div.related ul {70- padding: 0 0 0 10px;71-}72-73-div.related a {74- color: #444;75-}76-77-/* -- body styles ----------------------------------------------------------- */78-79-a {80- color: #004B6B;81- text-decoration: underline;82-}83-84-a:hover {85- color: #6D4100;86- text-decoration: underline;87-}88-89-div.body {90- padding-bottom: 40px; /* saved for footer */91-}92-93-div.body h1,94-div.body h2,95-div.body h3,96-div.body h4,97-div.body h5,98-div.body h6 {99- font-family: 'Garamond', 'Georgia', serif;100- font-weight: normal;101- margin: 30px 0px 10px 0px;102- padding: 0;103-}104-105-{% if theme_index_logo %}106-div.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 %}112-113-div.body h2 { font-size: 180%; }114-div.body h3 { font-size: 150%; }115-div.body h4 { font-size: 130%; }116-div.body h5 { font-size: 100%; }117-div.body h6 { font-size: 100%; }118-119-a.headerlink {120- color: white;121- padding: 0 4px;122- text-decoration: none;123-}124-125-a.headerlink:hover {126- color: #444;127- background: #eaeaea;128-}129-130-div.body p, div.body dd, div.body li {131- line-height: 1.4em;132-}133-134-div.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-}141-142-div.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-}150-151-div.admonition p.last {152- margin-bottom: 0;153-}154-155-div.highlight{156- background-color: white;157-}158-159-dt:target, .highlight {160- background: #FAF3E8;161-}162-163-div.note {164- background-color: #eee;165- border: 1px solid #ccc;166-}167-168-div.seealso {169- background-color: #ffc;170- border: 1px solid #ff6;171-}172-173-div.topic {174- background-color: #eee;175-}176-177-div.warning {178- background-color: #ffe4e4;179- border: 1px solid #f66;180-}181-182-p.admonition-title {183- display: inline;184-}185-186-p.admonition-title:after {187- content: ":";188-}189-190-pre, tt {191- font-family: 'Consolas', 'Menlo', 'Deja Vu Sans Mono', 'Bitstream Vera Sans Mono', monospace;192- font-size: 0.85em;193-}194-195-img.screenshot {196-}197-198-tt.descname, tt.descclassname {199- font-size: 0.95em;200-}201-202-tt.descname {203- padding-right: 0.08em;204-}205-206-img.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-}211-212-table.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-}218-219-table.docutils td, table.docutils th {220- border: 1px solid #888;221- padding: 0.25em 0.7em;222-}223-224-table.field-list, table.footnote {225- border: none;226- -moz-box-shadow: none;227- -webkit-box-shadow: none;228- box-shadow: none;229-}230-231-table.footnote {232- margin: 15px 0;233- width: 100%;234- border: 1px solid #eee;235-}236-237-table.field-list th {238- padding: 0 0.8em 0 0;239-}240-241-table.field-list td {242- padding: 0;243-}244-245-table.footnote td {246- padding: 0.5em;247-}248-249-dl {250- margin: 0;251- padding: 0;252-}253-254-dl dd {255- margin-left: 30px;256-}257-258-pre {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-}269-270-dl pre {271- margin-left: -60px;272- padding-left: 60px;273-}274-275-tt {276- background-color: #ecf0f3;277- color: #222;278- /* padding: 1px 2px; */279-}280-281-tt.xref, a tt {282- background-color: #FBFBFB;283-}284-285-a:hover tt {286- background: #EEE;287-}deleted:docs/_themes/kr_small/layout.html-22 removed
12345678910111213141516171819202122{% extends "basic/layout.html" %}{% block header %} {{ super() }} {% if pagename == 'index' %} <div class=indexwrapper> {% endif %}{% endblock %}{% block footer %} {% if pagename == 'index' %} </div> {% endif %}{% endblock %}{# do not display relbars #}{% block relbar1 %}{% endblock %}{% block relbar2 %} {% if theme_github_fork %} <a href="http://github.com/{{ theme_github_fork }}"><img style="position: fixed; top: 0; right: 0; border: 0;" src="http://s3.amazonaws.com/github/ribbons/forkme_right_darkblue_121621.png" alt="Fork me on GitHub" /></a> {% endif %}{% endblock %}{% block sidebar1 %}{% endblock %}{% block sidebar2 %}{% endblock %}deleted:docs/_themes/kr_small/theme.conf-10 removed
1-[theme]2-inherit = basic3-stylesheet = flasky.css4-nosidebar = true5-pygments_style = flask_theme_support.FlaskyStyle6-7-[options]8-index_logo = ''9-index_logo_height = 120px10-github_fork = ''deleted:docs/_themes/README.rst-25 removed
1-krTheme Sphinx Style2-====================3-4-This repository contains sphinx styles Kenneth Reitz uses in most of5-his projects. It is a derivative of Mitsuhiko's themes for Flask and Flask related6-projects. To use this style in your Sphinx documentation, follow7-this guide:8-9-1. put this folder as _themes into your docs folder. Alternatively10- you can also use git submodules to check out the contents there.11-12-2. add this to your conf.py: ::13-14- sys.path.append(os.path.abspath('_themes'))15- html_theme_path = ['_themes']16- html_theme = 'flask'17-18-The following themes exist:19-20-**kr**21- the standard flask documentation theme for large projects22-23-**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 line2 3 Contributor's Guide4 ===================5 6-If you're reading this you're probably interested in contributing to7-Requests. First, We'd like to say: thank you! Open source projects8-live-and-die based on the support they receive from others, and the fact that9-you're even considering supporting Requests is very generous of10-you.6+If you're reading this, you're probably interested in contributing to Requests.7+Thank you very much! Open source projects live-and-die based on the support8+they receive from others, and the fact that you're even considering9+contributing to the Requests project is *very* generous of you.10 12-This document lays out guidelines and advice for contributing to Requests.13-If you're thinking of contributing, start by reading this thoroughly and14-getting a feel for how contributing to the project works. If you have any11+This document lays out guidelines and advice for contributing to this project.12+If you're thinking of contributing, please start by reading this document and13+getting a feel for how contributing to this project works. If you have any14 questions, feel free to reach out to either `Ian Cordasco`_ or `Cory Benfield`_,15 the primary maintainers.16 18-The guide is split into sections based on the type of contribution you're19-thinking of making, with a section that covers general guidelines for all20-contributors.21-17 .. _Ian Cordasco: http://www.coglib.com/~icordasc/18 .. _Cory Benfield: https://lukasa.co.uk/about19 20+If you have non-technical feedback, philosophical ponderings, crazy ideas, or21+other general thoughts about Requests or its position within the Python22+ecosystem, the BDFL, `Kenneth Reitz`_, would love to hear from you.23 26-All Contributions27------------------24+The guide is split into sections based on the type of contribution you're25+thinking of making, with a section that covers general guidelines for all26+contributors.27 28+.. _Kenneth Reitz: mailto:me@kennethreitz.org29+30 Be Cordial30-~~~~~~~~~~31+----------32 32-**Be cordial or be on your way.**33+ **Be cordial or be on your way**. *—Kenneth Reitz*34 35 Requests has one very important rule governing all forms of contribution,36 including reporting bugs or requesting features. This golden rule is37+"`be cordial or be on your way`_".38+36-`be cordial or be on your way`_. **All contributions are welcome**, as long as39+**All contributions are welcome**, as long as40 everyone involved is treated with respect.41 42 .. _be cordial or be on your way: http://kennethreitz.org/be-cordial-or-be-on-your-way/43 44 .. _early-feedback:45 46 Get Early Feedback44-~~~~~~~~~~~~~~~~~~47+------------------48 49 If you are contributing, do not feel the need to sit on your contribution until50 it is perfectly polished and complete. It helps everyone involved for you to51 seek feedback as early as you possibly can. Submitting an early, unfinished1 unmodified line53 getting that contribution accepted, and can save you from putting a lot of work54 into a contribution that is not suitable for the project.55 56 Contribution Suitability54-~~~~~~~~~~~~~~~~~~~~~~~~57+------------------------58 56-The project maintainer has the last word on whether or not a contribution is57-suitable for Requests. All contributions will be considered, but from time58-to time contributions will be rejected because they do not suit the project.59+Our project maintainers have the last word on whether or not a contribution is60+suitable for Requests. All contributions will be considered carefully, but from61+time to time, contributions will be rejected because they do not suit the62+current goals or needs of the project.63 60-If your contribution is rejected, don't despair! So long as you followed these61-guidelines, you'll have a much better chance of getting your next contribution62-accepted.64+If your contribution is rejected, don't despair! As long as you followed these65+guidelines, you will have a much better chance of getting your next66+contribution accepted.67 68 69 Code Contributions70 ------------------71 68-Steps69-~~~~~72+Steps for Submitting Code73+~~~~~~~~~~~~~~~~~~~~~~~~~74 75 When contributing code, you'll want to follow this checklist:76 77 1. Fork the repository on GitHub.29 unmodified lines107 asking for help.108 109 Please also check the :ref:`early-feedback` section.110 111+Kenneth Reitz's Code Style™112+~~~~~~~~~~~~~~~~~~~~~~~~~~~113+114+The Requests codebase uses the `PEP 8`_ code style.115+116+In addition to the standards outlined in PEP 8, we have a few guidelines:117+118+- 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.121+122+Additionally, one of the styles that PEP8 recommends for `line continuations`_123+completely lacks all sense of taste, and is not to be permitted within124+the Requests codebase::125+126+ # Aligned with opening delimiter.127+ foo = long_function_name(var_one, var_two,128+ var_three, var_four)129+130+No. Just don't. Please.131+132+Docstrings are to follow the following syntaxes::133+134+ def the_earth_is_flat():135+ """NASA divided up the seas into thirty-three degrees."""136+ pass137+138+::139+140+ 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.148+149+ Spiral out. Keep going...150+ """151+ pass152+153+All functions, methods, and classes are to contain docstrings. Object data154+model methods (e.g. ``__repr__``) are typically the exception to this rule.155+156+Thanks for helping to make the world a better place!157+158+.. _PEP 8: http://pep8.org159+.. _line continuations: https://www.python.org/dev/peps/pep-0008/#indentation160+161 Documentation Contributions162 ---------------------------163 164 Documentation improvements are always welcome! The documentation files live in165 the ``docs/`` directory of the codebase. They're written in166 `reStructuredText`_, and use `Sphinx`_ to generate the full suite of167 documentation.168 115-When contributing documentation, please attempt to follow the style of the169+When contributing documentation, please do your best to follow the style of the170 documentation files. This means a soft-limit of 79 characters wide in your text117-files and a semi-formal prose style.171+files and a semi-formal, yet friendly and approachable, prose style.172 173+When presenting Python code, use single-quoted strings (``'hello'`` instead of174+``"hello"``).175+176 .. _reStructuredText: http://docutils.sourceforge.net/rst.html177 .. _Sphinx: http://sphinx-doc.org/index.html178 179 12 unmodified lines192 193 Feature Requests194 ----------------195 139-Requests is in a perpetual feature freeze. The maintainers believe that140-requests contains every major feature currently required by the vast majority141-of users.196+Requests is in a perpetual feature freeze, only the BDFL can add or approve of197+new features. The maintainers believe that Requests is a feature-complete198+piece of software at this time.199 200+One of the most important skills to have while maintaining a largely-used201+open source project is learning the ability to say "no" to suggested changes,202+while keeping an open ear and mind.203+204 If you believe there is a feature missing, feel free to raise a feature205 request, but please do be aware that the overwhelming likelihood is that your145-feature request will not be accepted.206+feature request will not be accepted.modified:docs/user/advanced.rst+47 added-29 removed
22 unmodified lines23 24 s = requests.Session()25 26 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')28 29 print(r.text)30 # '{"cookies": {"sessioncookie": "123456789"}}'31 17 unmodified lines49 requests, even if using a session. This example will only send the cookies50 with the first request, but not the second::51 52 s = requests.Session()53+54 r = s.get('http://httpbin.org/cookies', cookies={'from-my': 'browser'})55 print(r.text)56 # '{"cookies": {"from-my": "browser"}}'57 71 unmodified lines129 130 from requests import Request, Session131 132 s = Session()132- req = Request('GET', url,133- data=data,134- headers=header135- )133+134+ req = Request('POST', url, data=data, headers=headers)135 prepped = req.prepare()136 137 # do something with prepped.body138+ prepped.body = 'No, I want exactly this as the body.'139+140 # do something with prepped.headers141+ del prepped.headers['Content-Type']142 143 resp = s.send(prepped,144 stream=stream,145 verify=verify,20 unmodified lines166 167 from requests import Request, Session168 169 s = Session()168- req = Request('GET', url,169- data=data170- headers=headers171- )170+ req = Request('GET', url, data=data, headers=headers)171 172 prepped = s.prepare_request(req)173 174 # do something with prepped.body175+ prepped.body = 'Seriously, send exactly these bytes.'176+177 # do something with prepped.headers178+ prepped.headers['Keep-Dead'] = 'parrot'179 180 resp = s.send(prepped,181 stream=stream,182 verify=verify,38 unmodified lines221 You can also specify a local cert to use as client side certificate, as a single222 file (containing the private key and the certificate) or as a tuple of both223 file's path::224 223- >>> 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]>227 228 If you specify a wrong path or an invalid cert::229 228- >>> 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 lib232 233+.. warning:: The private key to your local certificate *must* be unencrypted.234+ Currently, requests does not support using encrypted keys.235+236 .. _ca-certificates:237 238 CA Certificates239 ---------------117 unmodified lines357 POST Multiple Multipart-Encoded Files358 -------------------------------------359 360 You can send multiple files in one request. For example, suppose you want to356-upload image files to an HTML form with a multiple file field 'images':361+upload image files to an HTML form with a multiple file field 'images'::362 363 <input type="file" name="images" multiple="true" required="true"/>364 360-To do that, just set files to a list of tuples of (form_field_name, file_info):365+To do that, just set files to a list of tuples of ``(form_field_name, file_info)``::366 367 >>> 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 lines493 the resulting iterator object instead::494 495 lines = r.iter_lines()496 # Save the first line for later or just skip it497+498 first_line = next(lines)499+500 for line in lines:501 print(line)502 503 .. _proxies:6 unmodified lines510 511 import requests512 513 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 }517 510- requests.get("http://example.org", proxies=proxies)518+ requests.get('http://example.org', proxies=proxies)519 520 You can also configure proxies by setting the environment variables521 ``HTTP_PROXY`` and ``HTTPS_PROXY``.522 523 ::524 525 $ export HTTP_PROXY="http://10.10.1.10:3128"526 $ export HTTPS_PROXY="http://10.10.1.10:1080"527+528 $ python529 >>> import requests521- >>> requests.get("http://example.org")530+ >>> requests.get('http://example.org')531 532 To use HTTP Basic Auth with your proxy, use the `http://user:password@host/` syntax::533 525- proxies = {526- "http": "http://user:pass@10.10.1.10:3128/",527- }534+ proxies = {'http': 'http://user:pass@10.10.1.10:3128/'}535 536 To give a proxy for a specific scheme and host, use the537 `scheme://hostname` form for the key. This will match for538 any request to the given scheme and exact hostname.539 540 ::541 535- 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'}543 544 Note that proxy URLs must include the scheme.545 546 .. _compliance:56 unmodified lines603 604 ::605 606 >>> commit_data = r.json()607+608 >>> print(commit_data.keys())609 [u'committer', u'author', u'url', u'tree', u'sha', u'parents', u'message']610+611 >>> 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'}613+614 >>> print(commit_data[u'message'])615 makin' history616 617 So far, so simple. Well, let's investigate the GitHub API a little bit. Now,31 unmodified lines649 650 >>> r = requests.get('https://api.github.com/repos/kennethreitz/requests/issues/482')651 >>> r.status_code652 200653+654 >>> issue = json.loads(r.text)655+656 >>> print(issue[u'title'])657 Feature any http verb in docs658+659 >>> print(issue[u'comments'])660 3661 662 Cool, we have three comments. Let's take a look at the last of them.2 unmodified lines665 666 >>> r = requests.get(r.url + u'/comments')667 >>> r.status_code668 200669+670 >>> comments = r.json()671+672 >>> print(comments[0].keys())673 [u'body', u'url', u'created_at', u'updated_at', u'user', u'id']674+675 >>> print(comments[2][u'body'])676 Probably in the "advanced" section677 678 Well, that seems like a silly place. Let's post a comment telling the poster11 unmodified lines690 ::691 692 >>> 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"694+695 >>> r = requests.post(url=url, data=body)696 >>> r.status_code697 404698 4 unmodified lines703 ::704 705 >>> from requests.auth import HTTPBasicAuth706 >>> auth = HTTPBasicAuth('fake@example.com', 'not_a_real_password')707+708 >>> r = requests.post(url=url, data=body, auth=auth)709 >>> r.status_code710 201711+712 >>> content = r.json()713 >>> print(content[u'body'])714 Sounds great! I'll get right on it.715 5 unmodified lines721 ::722 723 >>> print(content[u"id"])724 5804413725+726 >>> 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"728+729 >>> r = requests.patch(url=url, data=body, auth=auth)730 >>> r.status_code731 200732 112 unmodified lines845 class Ssl3HttpAdapter(HTTPAdapter):846 """"Transport adapter" that allows us to use SSLv3."""847 848 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)852 853 .. _`described here`: http://www.kennethreitz.org/essays/the-future-of-python-http854 .. _`urllib3`: https://github.com/shazow/urllib3855 58 unmodified linesmodified:docs/user/authentication.rst+2 added-2 removed
35 unmodified lines36 ~~~~~~~~~~~~~~~~~~~~37 38 If no authentication method is given with the ``auth`` argument, Requests will39 attempt to get the authentication credentials for the URL's hostname from the40-user's netrc file.40+user's netrc file. The netrc file overrides raw HTTP authentication headers41+set with `headers=`.42 43 If credentials for the hostname are found, the request is sent with HTTP Basic44 Auth.45 79 unmodified lines125 .. _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 lines6 This part of the documentation covers the installation of Requests.7 The first step to using any software package is getting it properly installed.8 9 10-Distribute & Pip11-----------------10+Pip Install Requests11+--------------------12 13-Installing Requests is simple with `pip <https://pip.pypa.io>`_, just run14-this in your terminal::13+To install Requests, simply run this simple command in your terminal of choice::14 15 $ pip install requests16 18-or, with `easy_install <http://pypi.python.org/pypi/setuptools>`_::17+If 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/>`_19+can guide you through the process.20 20- $ easy_install requests21+Get the Source Code22+-------------------23 22-But, you really `shouldn't do that <https://stackoverflow.com/questions/3220404/why-use-pip-over-easy-install>`_.23-24-25-Get the Code26-------------27-24 Requests is actively developed on GitHub, where the code is25 `always available <https://github.com/kennethreitz/requests>`_.26 27 You can either clone the public repository::28 29 $ git clone git://github.com/kennethreitz/requests.git30 35-Download the `tarball <https://github.com/kennethreitz/requests/tarball/master>`_::31+Or, download the `tarball <https://github.com/kennethreitz/requests/tarball/master>`_::32 33 $ curl -OL https://github.com/kennethreitz/requests/tarball/master34+ # optionally, zipball is also available (for Windows users).35 39-Or, download the `zipball <https://github.com/kennethreitz/requests/zipball/master>`_::36+Once you have a copy of the source, you can embed it in your own Python37+package, or install it into your site-packages easily::38 41- $ curl -OL https://github.com/kennethreitz/requests/zipball/master42-43-44-Once you have a copy of the source, you can embed it in your Python package,45-or install it into your site-packages easily::46-39 $ python setup.py installmodified:docs/user/quickstart.rst+25 added-9 removed
35 unmodified lines36 37 Requests' simple API means that all forms of HTTP request are as obvious. For38 example, this is how you make an HTTP POST request::39 40- >>> r = requests.post("http://httpbin.org/post", data = {"key":"value"})40+ >>> r = requests.post('http://httpbin.org/post', data = {'key':'value'})41 42 Nice, right? What about the other HTTP request types: PUT, DELETE, HEAD and43 OPTIONS? These are all just as simple::44 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")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')49 50 That's all well and good, but it's also only the start of what Requests can51 do.52 9 unmodified lines62 ``key1=value1`` and ``key2=value2`` to ``httpbin.org/get``, you would use the63 following code::64 65 >>> 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)67 68 You can see that the URL has been correctly encoded by printing the URL::69 70 >>> print(r.url)4 unmodified lines75 76 You can also pass a list of items as a value::77 78 >>> payload = {'key1': 'value1', 'key2': ['value2', 'value3']}79+79- >>> 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=value383 84 Response Content2 unmodified lines87 We can read the content of the server's response. Consider the GitHub timeline88 again::89 90 >>> import requests91+92 >>> r = requests.get('https://api.github.com/events')93 >>> r.text94 u'[{"repository":{"open_issues":0,"url":"https://github.com/...95 36 unmodified lines132 use the following code::133 134 >>> from PIL import Image135 >>> from StringIO import StringIO136+137 >>> i = Image.open(StringIO(r.content))138 139 140 JSON Response Content1 unmodified line142 143 There's also a builtin JSON decoder, in case you're dealing with JSON data::144 145 >>> import requests146+147 >>> 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 lines166 server, 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::168 169 >>> r = requests.get('https://api.github.com/events', stream=True)170+171 >>> r.raw172 <requests.packages.urllib3.response.HTTPResponse object at 0x101194810>173+174 >>> r.raw.read(10)175 '\x1f\x8b\x08\x00\x00\x00\x00\x00\x00\x03'176 177 In general, however, you should use a pattern like this to save what is being16 unmodified lines194 ``headers`` parameter.195 196 For example, we didn't specify our user-agent in the previous example::197 192- >>> import json198 >>> url = 'https://api.github.com/some/endpoint'199 >>> headers = {'user-agent': 'my-app/0.0.1'}200 201 >>> r = requests.get(url, headers=headers)202 203 Note: Custom headers are given less precedence than more specific sources of information. For instance:204 200-* 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 lines219 To do this, simply pass a dictionary to the ``data`` argument. Your220 dictionary of data will automatically be form-encoded when the request is made::221 222 >>> payload = {'key1': 'value1', 'key2': 'value2'}223+224 >>> r = requests.post("http://httpbin.org/post", data=payload)225 >>> print(r.text)226 {227 ...9 unmodified lines237 238 For example, the GitHub API v3 accepts JSON-Encoded POST/PATCH data::239 240 >>> import json241+242 >>> url = 'https://api.github.com/some/endpoint'243 >>> payload = {'some': 'data'}244 245 >>> r = requests.post(url, data=json.dumps(payload))186 unmodified lines432 433 For example, GitHub redirects all HTTP requests to HTTPS::434 435 >>> r = requests.get('http://github.com')436+437 >>> r.url438 'https://github.com/'439+440 >>> r.status_code441 200442+443 >>> r.history444 [<Response [301]>]445 446 447 If you're using GET, OPTIONS, POST, PUT, PATCH or DELETE, you can disable448 redirection handling with the ``allow_redirects`` parameter::449 450 >>> r = requests.get('http://github.com', allow_redirects=False)451+452 >>> r.status_code453 301454+455 >>> r.history456 []457 458 If you're using HEAD, you can enable redirection as well::459 460 >>> r = requests.head('http://github.com', allow_redirects=True)461+462 >>> r.url463 'https://github.com/'464+465 >>> r.history466 [<Response [301]>]467 468 41 unmodified linesmodified:docs/api.rst+48 added-52 removed
23 unmodified lines24 .. autofunction:: put25 .. autofunction:: patch26 .. autofunction:: delete27 28+Exceptions29+----------30 31+.. autoexception:: requests.RequestException32+.. autoexception:: requests.ConnectionError33+.. autoexception:: requests.HTTPError34+.. autoexception:: requests.URLRequired35+.. autoexception:: requests.TooManyRedirects36+.. autoexception:: requests.ConnectTimeout37+.. autoexception:: requests.ReadTimeout38+.. autoexception:: requests.Timeout39+40+41+Request Sessions42+----------------43+44+.. _sessionapi:45+46+.. autoclass:: Session47+ :inherited-members:48+49+50 Lower-Level Classes30-~~~~~~~~~~~~~~~~~~~51+-------------------52 53 .. autoclass:: requests.Request54 :inherited-members:55 56 .. autoclass:: Response57 :inherited-members:58 38-Request Sessions39-----------------59 41-.. autoclass:: Session60+Lower-Lower-Level Classes61+-------------------------62+63+.. autoclass:: requests.PreparedRequest64 :inherited-members:65 66 .. autoclass:: requests.adapters.HTTPAdapter67 :inherited-members:5 unmodified lines73 .. autoclass:: requests.auth.HTTPBasicAuth74 .. autoclass:: requests.auth.HTTPProxyAuth75 .. autoclass:: requests.auth.HTTPDigestAuth76 55-Exceptions56-~~~~~~~~~~77 58-.. 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.Timeout78 79+Encodings80+---------81 68-Status Code Lookup69-~~~~~~~~~~~~~~~~~~82+.. autofunction:: requests.utils.get_encodings_from_content83+.. autofunction:: requests.utils.get_encoding_from_headers84+.. autofunction:: requests.utils.get_unicode_from_response85 71-.. autofunction:: requests.codes86 73-::74-75- >>> requests.codes['temporary_redirect']76- 30777-78- >>> requests.codes.teapot79- 41880-81- >>> requests.codes['\o/']82- 20083-87 .. _api-cookies:88 89 Cookies87-~~~~~~~90+-------91 92 .. autofunction:: requests.utils.dict_from_cookiejar93 .. autofunction:: requests.utils.cookiejar_from_dict94 .. autofunction:: requests.utils.add_dict_to_cookiejar4 unmodified lines99 .. autoclass:: requests.cookies.CookieConflictError100 :inherited-members:101 102 100-Encodings101-~~~~~~~~~103 103-.. autofunction:: requests.utils.get_encodings_from_content104-.. autofunction:: requests.utils.get_encoding_from_headers105-.. autofunction:: requests.utils.get_unicode_from_response104+Status Code Lookup105+------------------106 107+.. autofunction:: requests.codes108 108-Classes109-~~~~~~~109+::110 111-.. autoclass:: requests.Response112- :inherited-members:111+ >>> requests.codes['temporary_redirect']112+ 307113 114-.. autoclass:: requests.Request115- :inherited-members:114+ >>> requests.codes.teapot115+ 418116 117-.. autoclass:: requests.PreparedRequest118- :inherited-members:117+ >>> requests.codes['\o/']118+ 200119 120-.. _sessionapi:120 122-.. autoclass:: requests.Session123- :inherited-members:121 125-.. autoclass:: requests.adapters.HTTPAdapter126- :inherited-members:127-128-122 Migrating to 1.x123 ----------------124 125 This section details the main differences between 0.x and 1.x and is meant50 unmodified lines176 177 import requests178 import logging179 187- # 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 = 1188 189 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 linesmodified: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.14 14-import sys, os15+import sys16+import os17 18 # 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('.'))22+23+# Insert Requests' path into the system.24 sys.path.insert(0, os.path.abspath('..'))25+sys.path.insert(0, os.path.abspath('_themes'))26+27 import requests28 from requests import __version__29 23-# -- General configuration -----------------------------------------------------30 31+# -- General configuration ------------------------------------------------32+33 # If your documentation needs a minimal Sphinx version, state it here.34 #needs_sphinx = '1.0'35 28-# 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.39 extensions = [40 'sphinx.ext.autodoc',41 'sphinx.ext.intersphinx',42+ 'sphinx.ext.todo',43+ 'sphinx.ext.viewcode',44 ]45 46 # Add any paths that contain templates here, relative to this directory.47 templates_path = ['_templates']48 38-# 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']52 source_suffix = '.rst'53 54 # The encoding of source files.55 #source_encoding = 'utf-8-sig'2 unmodified lines58 master_doc = 'index'59 60 # General information about the project.61 project = u'Requests'49-copyright = u'2015. A <a href="http://kennethreitz.com/pages/open-projects.html">Kenneth Reitz</a> Project'62+copyright = u'2016. A <a href="http://kennethreitz.com/pages/open-projects.html">Kenneth Reitz</a> Project'63+author = u'Kenneth Reitz'64 65 # 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.70 version = __version__71 # The full version, including alpha/beta/rc tags.58-release = version72+release = __version__73 74 # 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 = None79+language = None80 81 # There are two options for replacing |today|: either, you set today to some82 # non-false value, then it is used:83 #today = ''3 unmodified lines87 # List of patterns, relative to source directory, that match files and88 # directories to ignore when looking for source files.89 exclude_patterns = ['_build']90 74-# 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 = None94 95 # If true, '()' will be appended to :func: etc. cross-reference text.78-#add_function_parentheses = True96+add_function_parentheses = False97 98 # If true, the current module name will be prepended to all description99 # unit titles (such as .. function::).82-#add_module_names = True100+add_module_names = True101 102 # If true, sectionauthor and moduleauthor directives will be shown in the103 # output. They are ignored by default.104 #show_authors = False3 unmodified lines108 109 # A list of ignored prefixes for module index sorting.110 #modindex_common_prefix = []111 112+# If true, keep warnings as "system message" paragraphs in the built documents.113+#keep_warnings = False114 95-# -- Options for HTML output ---------------------------------------------------115+# If true, `todo` and `todoList` produce output, else they produce nothing.116+todo_include_todos = True117 118+119+# -- Options for HTML output ----------------------------------------------120+121 # The theme to use for HTML and HTML Help pages. See the documentation for122 # a list of builtin themes.99-html_theme = 'default'123+html_theme = 'alabaster'124 125 # 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 = {}128+html_theme_options = {129+ 'show_powered_by': False,130+ 'github_user': 'kennethreitz',131+ 'github_repo': 'requests',132+ 'github_banner': True,133+ 'show_related': False134+}135 136 # Add any paths that contain custom themes here, relative to this directory.137 #html_theme_path = []138 7 unmodified lines146 # The name of an image file (relative to this directory) to place at the top147 # of the sidebar.148 #html_logo = None149 120-150 # 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 = None2 unmodified lines156 # 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".158 html_static_path = ['_static']159 160+# 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 = []164+165 # 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'168 169 # If true, SmartyPants will be used to convert quotes and dashes to170 # typographically correct entities.137-#html_use_smartypants = True171+html_use_smartypants = False172 173 # Custom sidebar templates, maps document names to template names.174 html_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 }180 181 # Additional templates that should be rendered to pages, maps page names to182 # template names.14 unmodified lines197 # If true, "Created using Sphinx" is shown in the HTML footer. Default is True.198 html_show_sphinx = False199 200 # If true, "(C) Copyright ..." is shown in the HTML footer. Default is True.166-#html_show_copyright = True201+html_show_copyright = True202 203 # 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 line207 208 # This is the file name suffix for HTML files (e.g. ".xhtml").209 #html_file_suffix = None210 211+# 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'216+217+# 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'}220+221+# 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'224+225 # Output file base name for HTML help builder.226 htmlhelp_basename = 'Requestsdoc'227 228+# -- Options for LaTeX output ---------------------------------------------229 180-# -- Options for LaTeX output --------------------------------------------------230+latex_elements = {231+# The paper size ('letterpaper' or 'a4paper').232+#'papersize': 'letterpaper',233 182-# The paper size ('letter' or 'a4').183-#latex_paper_size = 'letter'184-234 # The font size ('10pt', '11pt' or '12pt').186-#latex_font_size = '10pt'235+#'pointsize': '10pt',236 237+# Additional stuff for the LaTeX preamble.238+#'preamble': '',239+240+# Latex figure (float) alignment241+#'figure_align': 'htbp',242+}243+244 # 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]).247 latex_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 ]251 252 # The name of an image file (relative to this directory) to place at the top of253 # the title page.8 unmodified lines262 263 # If true, show URL addresses after external links.264 #latex_show_urls = False265 209-# Additional stuff for the LaTeX preamble.210-#latex_preamble = ''211-266 # Documents to append as an appendix to all manuals.267 #latex_appendices = []268 269 # If false, no module index is generated.270 #latex_domain_indices = True271 272 219-# -- Options for manual page output --------------------------------------------273+# -- Options for manual page output ---------------------------------------274 275 # One entry per manual page. List of tuples276 # (source start file, name, description, authors, manual section).277 man_pages = [224- ('index', 'requests', u'Requests Documentation',225- [u'Kenneth Reitz'], 1)278+ (master_doc, 'requests', u'Requests Documentation',279+ [author], 1)280 ]281 282 # If true, show URL addresses after external links.283 #man_show_urls = False284 231-# -- Options for Texinfo output ------------------------------------------------285 286+# -- Options for Texinfo output -------------------------------------------287+288 # Grouping the document tree into Texinfo files. List of tuples289 # (source start file, target name, title, author,290 # dir menu entry, description, category)291 texinfo_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 ]296 297 # Documents to append as an appendix to all manuals.242-texinfo_appendices = []298+#texinfo_appendices = []299 244-sys.path.append(os.path.abspath('_themes'))245-html_theme_path = ['_themes']246-html_theme = 'kr'300+# If false, no module index is generated.301+#texinfo_domain_indices = True302 303+# How to display URL addresses: 'footnote', 'no', or 'inline'.304+#texinfo_show_urls = 'footnote'305+306+# If true, do not generate a @detailmenu in the "Top" node's menu.307+#texinfo_no_detailmenu = False308+309+310+# -- Options for Epub output ----------------------------------------------311+312+# Bibliographic Dublin Core info.313+epub_title = project314+epub_author = author315+epub_publisher = author316+epub_copyright = copyright317+318+# The basename for the epub file. It defaults to the project name.319+#epub_basename = project320+321+# 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'326+327+# The language of the text. It defaults to the language option328+# or 'en' if the language is not set.329+#epub_language = ''330+331+# The scheme of the identifier. Typical schemes are ISBN or URL.332+#epub_scheme = ''333+334+# The unique identifier of the text. This can be a ISBN number335+# or the project homepage.336+#epub_identifier = ''337+338+# A unique identification for the text.339+#epub_uid = ''340+341+# A tuple containing the cover image and cover page html template filenames.342+#epub_cover = ()343+344+# A sequence of (type, uri, title) tuples for the guide element of content.opf.345+#epub_guide = ()346+347+# 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 = []350+351+# 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 = []354+355+# A list of files that should not be packed into the epub file.356+epub_exclude_files = ['search.html']357+358+# The depth of the table of contents in toc.ncx.359+#epub_tocdepth = 3360+361+# Allow duplicate toc entries.362+#epub_tocdup = True363+364+# Choose between 'default' and 'includehidden'.365+#epub_tocscope = 'default'366+367+# Fix unsupported image types using the Pillow.368+#epub_fix_images = False369+370+# Scale large images.371+#epub_max_image_width = 0372+373+# How to display URL addresses: 'footnote', 'no', or 'inline'.374+#epub_show_urls = 'inline'375+376+# If false, no index is generated.377+#epub_use_index = True378+379 intersphinx_mapping = {'urllib3': ('http://urllib3.readthedocs.org/en/latest', None)}modified:docs/index.rst+41 added-35 removed
6 unmodified lines7 =========================8 9 Release v\ |version|. (:ref:`Installation <install>`)10 11-Requests is an :ref:`Apache2 Licensed <apache2>` HTTP library, written in12-Python, for human beings.11+Requests is the only *Non-GMO* HTTP library for Python, safe for human12+consumption.13 14-Python's standard **urllib2** module provides most of15-the HTTP capabilities you need, but the API is thoroughly **broken**.16-It was built for a different time — and a different web. It requires an17-*enormous* amount of work (even method overrides) to perform the simplest of18-tasks.14+**Warning:** Recreational use of other HTTP libraries may result in dangerous side-effects,15+including: security vulnerabilities, verbose code, reinventing the wheel,16+constantly reading documentation, depression, headaches, or even death.17 20-Things shouldn’t be this way. Not in Python.18+Behold, the power of Requests::19 22-::23-20 >>> r = requests.get('https://api.github.com/user', auth=('user', 'pass'))21 >>> r.status_code22 20023 >>> r.headers['content-type']4 unmodified lines28 u'{"type":"User"...'29 >>> r.json()30 {u'private_gists': 419, u'total_private_repos': 77, ...}31 36-See `similar code, without Requests <https://gist.github.com/973705>`_.32+See `similar code, sans Requests <https://gist.github.com/973705>`_.33 38-Requests takes all of the work out of Python HTTP/1.1 — making your integration39-with web services seamless. There's no need to manually add query strings to40-your URLs, or to form-encode your POST data. Keep-alive and HTTP connection41-pooling are 100% automatic, powered by `urllib3 <https://github.com/shazow/urllib3>`_,34+35+Requests allows you to send *organic, grass-fed* HTTP/1.1 requests, without the36+need for manual labor. There's no need to manually add query strings to your37+URLs, or to form-encode your POST data. Keep-alive and HTTP connection pooling38+are 100% automatic, powered by `urllib3 <https://github.com/shazow/urllib3>`_,39 which is embedded within Requests.40 41+User Testimonials42+-----------------43 45-Testimonials46-------------47-44 Her Majesty's Government, Amazon, Google, Twilio, Runscope, Mozilla, Heroku,45 PayPal, NPR, Obama for America, Transifex, Native Instruments, The Washington50-Post, Twitter, SoundCloud, Kippt, Readability, Sony, and Federal US Institutions that prefer to be unnamed51-use Requests internally. It has been downloaded over 60,000,000 times from PyPI.46+Post, Twitter, SoundCloud, Kippt, Readability, Sony, and Federal U.S.47+Institutions that prefer to be unnamed claim to use Requests internally.48 49 **Armin Ronacher**50 Requests is the perfect example how beautiful an API can be with the51 right level of abstraction.9 unmodified lines61 **Kenny Meyers**62 Python HTTP: When in doubt, or when not in doubt, use Requests. Beautiful,63 simple, Pythonic.64 65+Requests is one of the most downloaded Python packages of all time, pulling in66+over 7,000,000 downloads every month. All the cool kids are doing it!67 70-Feature Support71----------------68+Supported Features69+------------------70 71 Requests is ready for today's web.72 73 - International Domains and URLs2 unmodified lines76 - 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-safety89 90+Requests supports Python 2.6 — 3.5, and runs great on PyPy.91 90-User Guide91-----------92 93+The User Guide94+--------------95+96 This part of the documentation, which is mostly prose, begins with some97 background information about Requests, then focuses on step-by-step98 instructions for getting the most out of Requests.99 6 unmodified lines106 user/advanced107 user/authentication108 109 107-Community Guide108------------------110+The Community Guide111+-------------------112 113 This part of the documentation, which is mostly prose, details the114 Requests ecosystem and community.115 7 unmodified lines123 community/vulnerabilities124 community/updates125 community/release-process126 124-API Documentation125------------------127+The API Documentation / Guide128+-----------------------------129 127-If you are looking for information on a specific function, class or method,130+If you are looking for information on a specific function, class, or method,131 this part of the documentation is for you.132 133 .. toctree::134 :maxdepth: 2135 136 api137 138 136-Contributor Guide137------------------139+The Contributor Guide140+---------------------141 142 If you want to contribute to the project, this part of the documentation is for143 you.144 145 .. toctree::143- :maxdepth: 1146+ :maxdepth: 3147 148 dev/contributing149 dev/philosophy150 dev/todo151 dev/authors152+153+There are no more guides. You are now guideless.154+Good luck.modified:docs/make.bat+263 added-190 removed
1-@ECHO OFF2-3-REM Command file for Sphinx documentation4-5-if "%SPHINXBUILD%" == "" (6- set SPHINXBUILD=sphinx-build7-)8-set BUILDDIR=_build9-set ALLSPHINXOPTS=-d %BUILDDIR%/doctrees %SPHINXOPTS% .10-set I18NSPHINXOPTS=%SPHINXOPTS% .11-if NOT "%PAPER%" == "" (12- set ALLSPHINXOPTS=-D latex_paper_size=%PAPER% %ALLSPHINXOPTS%13- set I18NSPHINXOPTS=-D latex_paper_size=%PAPER% %I18NSPHINXOPTS%14-)15-16-if "%1" == "" goto help17-18-if "%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-)40-41-if "%1" == "clean" (42- for /d %%i in (%BUILDDIR%\*) do rmdir /q /s %%i43- del /q /s %BUILDDIR%\*44- goto end45-)46-47-if "%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-)54-55-if "%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-)62-63-if "%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-)70-71-if "%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-)78-79-if "%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-)86-87-if "%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-)95-96-if "%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-)107-108-if "%1" == "devhelp" (109- %SPHINXBUILD% -b devhelp %ALLSPHINXOPTS% %BUILDDIR%/devhelp110- if errorlevel 1 exit /b 1111- echo.112- echo.Build finished.113- goto end114-)115-116-if "%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-)123-124-if "%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-)131-132-if "%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-)139-140-if "%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-)147-148-if "%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-)155-156-if "%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-)163-164-if "%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-)171-172-if "%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 ^177-or in %BUILDDIR%/linkcheck/output.txt.178- goto end179-)180-181-if "%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 ^186-results in %BUILDDIR%/doctest/output.txt.187- goto end188-)189-190-:end1+@ECHO OFF2+3+REM Command file for Sphinx documentation4+5+if "%SPHINXBUILD%" == "" (6+ set SPHINXBUILD=sphinx-build7+)8+set BUILDDIR=_build9+set ALLSPHINXOPTS=-d %BUILDDIR%/doctrees %SPHINXOPTS% .10+set I18NSPHINXOPTS=%SPHINXOPTS% .11+if NOT "%PAPER%" == "" (12+ set ALLSPHINXOPTS=-D latex_paper_size=%PAPER% %ALLSPHINXOPTS%13+ set I18NSPHINXOPTS=-D latex_paper_size=%PAPER% %I18NSPHINXOPTS%14+)15+16+if "%1" == "" goto help17+18+if "%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+)43+44+if "%1" == "clean" (45+ for /d %%i in (%BUILDDIR%\*) do rmdir /q /s %%i46+ del /q /s %BUILDDIR%\*47+ goto end48+)49+50+51+REM Check if sphinx-build is available and fallback to Python version if any52+%SPHINXBUILD% 1>NUL 2>NUL53+if errorlevel 9009 goto sphinx_python54+goto sphinx_ok55+56+:sphinx_python57+58+set SPHINXBUILD=python -m sphinx.__init__59+%SPHINXBUILD% 2> nul60+if 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+)71+72+:sphinx_ok73+74+75+if "%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+)82+83+if "%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+)90+91+if "%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+)98+99+if "%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+)106+107+if "%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+)114+115+if "%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+)123+124+if "%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+)135+136+if "%1" == "devhelp" (137+ %SPHINXBUILD% -b devhelp %ALLSPHINXOPTS% %BUILDDIR%/devhelp138+ if errorlevel 1 exit /b 1139+ echo.140+ echo.Build finished.141+ goto end142+)143+144+if "%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+)151+152+if "%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+)159+160+if "%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+)169+170+if "%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+)179+180+if "%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+)187+188+if "%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+)195+196+if "%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+)203+204+if "%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+)211+212+if "%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+)219+220+if "%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 ^225+or in %BUILDDIR%/linkcheck/output.txt.226+ goto end227+)228+229+if "%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 ^234+results in %BUILDDIR%/doctest/output.txt.235+ goto end236+)237+238+if "%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 ^243+results in %BUILDDIR%/coverage/python.txt.244+ goto end245+)246+247+if "%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+)254+255+if "%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+)262+263+:endmodified:docs/Makefile+67 added-4 removed
5 unmodified lines6 SPHINXBUILD = sphinx-build7 PAPER =8 BUILDDIR = _build9 10+# User-friendly check for sphinx-build11+ifeq ($(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/)13+endif14+15 # Internal variables.16 PAPEROPT_a4 = -D latex_paper_size=a417 PAPEROPT_letter = -D latex_paper_size=letter18 ALLSPHINXOPTS = -d $(BUILDDIR)/doctrees $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) .19 # the i18n builder cannot share the environment and doctrees with the others20 I18NSPHINXOPTS = $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) .21 17-.PHONY: help clean html dirhtml singlehtml pickle json htmlhelp qthelp devhelp epub latex latexpdf text man changes linkcheck doctest gettext18-22+.PHONY: help23 help: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 line28 @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)"49 50+.PHONY: clean51 clean:42- -rm -rf $(BUILDDIR)/*52+ rm -rf $(BUILDDIR)/*53 54+.PHONY: html55 html:56 $(SPHINXBUILD) -b html $(ALLSPHINXOPTS) $(BUILDDIR)/html57 @echo58 @echo "Build finished. The HTML pages are in $(BUILDDIR)/html."59 60+.PHONY: dirhtml61 dirhtml:62 $(SPHINXBUILD) -b dirhtml $(ALLSPHINXOPTS) $(BUILDDIR)/dirhtml63 @echo64 @echo "Build finished. The HTML pages are in $(BUILDDIR)/dirhtml."65 66+.PHONY: singlehtml67 singlehtml:68 $(SPHINXBUILD) -b singlehtml $(ALLSPHINXOPTS) $(BUILDDIR)/singlehtml69 @echo70 @echo "Build finished. The HTML page is in $(BUILDDIR)/singlehtml."71 72+.PHONY: pickle73 pickle:74 $(SPHINXBUILD) -b pickle $(ALLSPHINXOPTS) $(BUILDDIR)/pickle75 @echo76 @echo "Build finished; now you can process the pickle files."77 78+.PHONY: json79 json:80 $(SPHINXBUILD) -b json $(ALLSPHINXOPTS) $(BUILDDIR)/json81 @echo82 @echo "Build finished; now you can process the JSON files."83 84+.PHONY: htmlhelp85 htmlhelp: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."90 91+.PHONY: qthelp92 qthelp:93 $(SPHINXBUILD) -b qthelp $(ALLSPHINXOPTS) $(BUILDDIR)/qthelp94 @echo95 @echo "Build finished; now you can run "qcollectiongenerator" with the" \1 unmodified line97 @echo "# qcollectiongenerator $(BUILDDIR)/qthelp/Requests.qhcp"98 @echo "To view the help file:"99 @echo "# assistant -collectionFile $(BUILDDIR)/qthelp/Requests.qhc"100 101+.PHONY: applehelp102+applehelp: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."109+110+.PHONY: devhelp111 devhelp:112 $(SPHINXBUILD) -b devhelp $(ALLSPHINXOPTS) $(BUILDDIR)/devhelp113 @echo114 @echo "Build finished."1 unmodified line116 @echo "# mkdir -p $$HOME/.local/share/devhelp/Requests"117 @echo "# ln -s $(BUILDDIR)/devhelp $$HOME/.local/share/devhelp/Requests"118 @echo "# devhelp"119 120+.PHONY: epub121 epub:122 $(SPHINXBUILD) -b epub $(ALLSPHINXOPTS) $(BUILDDIR)/epub123 @echo124 @echo "Build finished. The epub file is in $(BUILDDIR)/epub."125 126+.PHONY: latex127 latex: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)."133 134+.PHONY: latexpdf135 latexpdf: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."140 141+.PHONY: latexpdfja142+latexpdfja: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."147+148+.PHONY: text149 text:150 $(SPHINXBUILD) -b text $(ALLSPHINXOPTS) $(BUILDDIR)/text151 @echo152 @echo "Build finished. The text files are in $(BUILDDIR)/text."153 154+.PHONY: man155 man:156 $(SPHINXBUILD) -b man $(ALLSPHINXOPTS) $(BUILDDIR)/man157 @echo158 @echo "Build finished. The manual pages are in $(BUILDDIR)/man."159 160+.PHONY: texinfo161 texinfo: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)."167 168+.PHONY: info169 info: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."174 175+.PHONY: gettext176 gettext:177 $(SPHINXBUILD) -b gettext $(I18NSPHINXOPTS) $(BUILDDIR)/locale178 @echo179 @echo "Build finished. The message catalogs are in $(BUILDDIR)/locale."180 181+.PHONY: changes182 changes:183 $(SPHINXBUILD) -b changes $(ALLSPHINXOPTS) $(BUILDDIR)/changes184 @echo185 @echo "The overview file is in $(BUILDDIR)/changes."186 187+.PHONY: linkcheck188 linkcheck: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."193 194+.PHONY: doctest195 doctest: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."199+200+.PHONY: coverage201+coverage: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."205+206+.PHONY: xml207+xml:208+ $(SPHINXBUILD) -b xml $(ALLSPHINXOPTS) $(BUILDDIR)/xml209+ @echo210+ @echo "Build finished. The XML files are in $(BUILDDIR)/xml."211+212+.PHONY: pseudoxml213+pseudoxml: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
1-include HISTORY.rst README.rst LICENSEdeleted:docs/requirements.txt-1 removed
1-Sphinx==1.1.3modified:requests/packages/urllib3/contrib/appengine.py+12 added-11 removed
1+from __future__ import absolute_import2 import logging3 import os4 import warnings5 54 unmodified lines60 if not urlfetch:61 raise AppEnginePlatformError(62 "URLFetch is not available in this environment.")63 63- 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 lines108 except urlfetch.DeadlineExceededError as e:109 raise TimeoutError(self, e)110 111 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)117 118 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)122 123 except urlfetch.ResponseTooLargeError as e:31 unmodified lines155 return http_response156 157 def _urlfetch_response_to_http_response(self, urlfetch_resp, **response_kw):158 158- 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 lines176 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.total14 unmodified lines199 200 201 def 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())205 206 207 def is_appengine_sandbox():207- return is_appengine() and not is_prod_appengine_v2()208+ return is_appengine() and not is_prod_appengine_mvms()209 210 211 def is_local_appengine():212 return ('APPENGINE_RUNTIME' in os.environ and213 'Development/' in os.environ['SERVER_SOFTWARE'])214 215 215-def is_prod_appengine_v1():216+def 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())220 221 221-def is_prod_appengine_v2():222+def is_prod_appengine_mvms():223 return os.environ.get('GAE_VM', False) == 'true'modified:requests/packages/urllib3/contrib/ntlmpool.py+1 added
1 unmodified line2 NTLM authenticating pool, contributed by erikcederstran3 4 Issue #10, see: http://code.google.com/p/urllib3/issues/detail?id=105 """6+from __future__ import absolute_import7 8 try:9 from http.client import HTTPSConnection10 except ImportError:105 unmodified linesmodified:requests/packages/urllib3/contrib/pyopenssl.py+18 added-17 removed
41 unmodified lines42 .. _sni: https://en.wikipedia.org/wiki/Server_Name_Indication43 .. _crime attack: https://en.wikipedia.org/wiki/CRIME_(security_exploit)44 45 '''46+from __future__ import absolute_import47 48 try:49 from ndg.httpsclient.ssl_peer_verification import SUBJ_ALT_NAME_SUPPORT50 from ndg.httpsclient.subj_alt_name import SubjectAltName as BaseSubjectAltName2 unmodified lines53 54 import OpenSSL.SSL55 from pyasn1.codec.der import decoder as der_decoder56 from pyasn1.type import univ, constraint56-from socket import _fileobject, timeout57+from socket import _fileobject, timeout, error as SocketError58 import ssl59 import select60 61 from .. import connection9 unmodified lines71 ssl.PROTOCOL_SSLv23: OpenSSL.SSL.SSLv23_METHOD,72 ssl.PROTOCOL_TLSv1: OpenSSL.SSL.TLSv1_METHOD,73 }74 75+if hasattr(ssl, 'PROTOCOL_TLSv1_1') and hasattr(OpenSSL.SSL, 'TLSv1_1_METHOD'):76+ _openssl_versions[ssl.PROTOCOL_TLSv1_1] = OpenSSL.SSL.TLSv1_1_METHOD77+78+if hasattr(ssl, 'PROTOCOL_TLSv1_2') and hasattr(OpenSSL.SSL, 'TLSv1_2_METHOD'):79+ _openssl_versions[ssl.PROTOCOL_TLSv1_2] = OpenSSL.SSL.TLSv1_2_METHOD80+81 try:82 _openssl_versions.update({ssl.PROTOCOL_SSLv3: OpenSSL.SSL.SSLv3_METHOD})83 except AttributeError:84 pass85 86 _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 }92 93 DEFAULT_SSL_CIPHER_LIST = util.ssl_.DEFAULT_CIPHERS94 95 # OpenSSL will only write 16K at a time96 SSL_WRITE_BLOCKSIZE = 1638497 91-try:92- _ = memoryview93- has_memoryview = True94-except NameError:95- has_memoryview = False96-98 orig_util_HAS_SNI = util.HAS_SNI99 orig_connection_ssl_wrap_socket = connection.ssl_wrap_socket100 101 10 unmodified lines112 connection.ssl_wrap_socket = orig_connection_ssl_wrap_socket113 util.HAS_SNI = orig_util_HAS_SNI114 115 115-### 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.117 class SubjectAltName(BaseSubjectAltName):118 '''ASN.1 implementation for subjectAltNames support'''119 120 # There is no limit to how many SAN certificates a certificate may have,2 unmodified lines123 sizeSpec = univ.SequenceOf.sizeSpec + \124 constraint.ValueSizeConstraint(1, 1024)125 126 126-### 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.128 def get_subj_alt_name(peer_cert):129 # Search through extensions130 dns_name = []131 if not SUBJ_ALT_NAME_SUPPORT:49 unmodified lines181 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 lines212 raise timeout()213 continue214 215 def sendall(self, data):215- if has_memoryview and not isinstance(data, memoryview):216- data = memoryview(data)217-216 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 += sent220 221 def shutdown(self):222 # FIXME rethrow compatible exceptions should we ever use this223 self.connection.shutdown()224 225 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 -= 1233 234 def getpeercert(self, binary_form=False):76 unmodified linesadded:requests/packages/urllib3/packages/ssl_match_hostname/.gitignore+1 added
1+envmodified:requests/packages/urllib3/packages/__init__.py+1 added
1 from __future__ import absolute_import2 3 from . import ssl_match_hostname4 5+__all__ = ('ssl_match_hostname', )modified:requests/packages/urllib3/util/__init__.py+20 added
1+from __future__ import absolute_import2 # For backwards compatibility, provide imports that used to be here.3 from .connection import is_connection_dropped4 from .request import make_headers5 from .response import is_fp_closed16 unmodified lines22 parse_url,23 split_first,24 Url,25 )26+27+__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
1+from __future__ import absolute_import2 import socket3 try:4 from select import poll, POLLIN5 except ImportError: # `poll` doesn't exist on OSX and other platforms96 unmodified linesmodified:requests/packages/urllib3/util/request.py+1 added
1+from __future__ import absolute_import2 from base64 import b64encode3 4 from ..packages.six import b5 67 unmodified linesmodified:requests/packages/urllib3/util/response.py+2 added-1 removed
1+from __future__ import absolute_import2 from ..packages.six.moves import http_client as httplib3 4 from ..exceptions import HeaderParsingError5 38 unmodified lines44 45 # 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)))50 51 defects = getattr(headers, 'defects', None)52 get_payload = getattr(headers, 'get_payload', None)22 unmodified linesmodified:requests/packages/urllib3/util/retry.py+4 added-3 removed
1+from __future__ import absolute_import2 import time3 import logging4 5 from ..exceptions import (120 unmodified lines126 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?131 132 def new(self, **kw):133 params = dict(134 total=self.total,71 unmodified lines206 return False207 208 return min(retry_counts) < 0209 209- 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.213 214 :param response: A response object, or None, if the server did not215 return a response.59 unmodified lines275 log.debug("Incremented Retry for (url='%s'): %r" % (url, new_retry))276 277 return new_retry278 277-279 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 linesmodified:requests/packages/urllib3/util/ssl_.py+35 added-4 removed
1+from __future__ import absolute_import2+import errno3+import warnings4+import hmac5+6 from binascii import hexlify, unhexlify7 from hashlib import md5, sha1, sha2568 4-from ..exceptions import SSLError, InsecurePlatformWarning9+from ..exceptions import SSLError, InsecurePlatformWarning, SNIMissingWarning10 11 12 SSLContext = None13 HAS_SNI = False5 unmodified lines19 40: sha1,20 64: sha256,21 }22 18-import errno19-import warnings23 24+def _const_compare_digest_backport(a, b):25+ """26+ Compare two digests of equal length in constant time.27+28+ 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 == 035+36+37+_const_compare_digest = getattr(hmac, 'compare_digest',38+ _const_compare_digest_backport)39+40+41 try: # Test for SSL features42 import ssl43 from ssl import wrap_socket, CERT_NONE, PROTOCOL_SSLv2344 from ssl import HAS_SNI # Has SNI?108 unmodified lines153 fingerprint_bytes = unhexlify(fingerprint.encode())154 155 cert_digest = hashfunc(cert).digest()156 137- 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)))160 161 140 unmodified lines302 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)306+307+ 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
1+from __future__ import absolute_import2 # The default socket timeout, used by httplib to indicate that no timeout was3 # specified by the user4 from socket import _GLOBAL_DEFAULT_TIMEOUT5 import time3 unmodified lines9 # A sentinel value to indicate that no timeout was specified by the user in10 # urllib311 _Default = object()12 13+14 def current_time():15 """16 Retrieve the current time. This function is mocked out in unit testing.17 """209 unmodified lines227 :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 linesmodified:requests/packages/urllib3/util/url.py+4 added-1 removed
1+from __future__ import absolute_import2 from collections import namedtuple3 4 from ..exceptions import LocationParseError5 79 unmodified lines85 86 def __str__(self):87 return self.url88 89+90 def 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 lines116 117 if min_idx is None or min_idx < 0:118 return s, '', None119 118- return s[:min_idx], s[min_idx+1:], min_delim120+ return s[:min_idx], s[min_idx + 1:], min_delim121 122 123 def parse_url(url):124 """82 unmodified lines207 path, query = path.split('?', 1)208 209 return Url(scheme, auth, host, port, path, query, fragment)210 211+212 def get_host(url):213 """214 Deprecated. Use :func:`.parse_url` instead.215 """2 unmodified linesmodified:requests/packages/urllib3/__init__.py+27 added-5 removed
1 """2 urllib3 - Thread-safe connection pooling and re-using.3 """4 5-__author__ = 'Andrey Petrov (andrey.petrov@shazow.net)'6-__license__ = 'MIT'7-__version__ = '1.12'5+from __future__ import absolute_import6+import warnings7 9-8 from .connectionpool import (9 HTTPConnectionPool,10 HTTPSConnectionPool,11 connection_from_url17 unmodified lines29 class NullHandler(logging.Handler):30 def emit(self, record):31 pass32 33+__author__ = 'Andrey Petrov (andrey.petrov@shazow.net)'34+__license__ = 'MIT'35+__version__ = '1.13.1'36+37+__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+)53+54 logging.getLogger(__name__).addHandler(NullHandler())55 56+57 def add_stderr_logger(level=logging.DEBUG):58 """59 Helper for quickly adding a StreamHandler to the logger. Useful for60 debugging.13 unmodified lines74 # ... Clean up.75 del NullHandler76 77 58-import warnings78 # SecurityWarning's always go off by default.79 warnings.simplefilter('always', exceptions.SecurityWarning, append=True)80 # SubjectAltNameWarning's should go off once per host81 warnings.simplefilter('default', exceptions.SubjectAltNameWarning)82 # InsecurePlatformWarning's don't vary between requests, so we keep it default.83 warnings.simplefilter('default', exceptions.InsecurePlatformWarning,84 append=True)85+# SNIMissingWarnings should go off only once.86+warnings.simplefilter('default', exceptions.SNIMissingWarning)87 88+89 def disable_warnings(category=exceptions.HTTPWarning):90 """91 Helper for quickly disabling all urllib3 warnings.92 """1 unmodified linemodified:requests/packages/urllib3/_collections.py+4 added-3 removed
1+from __future__ import absolute_import2 from collections import Mapping, MutableMapping3 try:4 from threading import RLock5 except ImportError: # Platform-specific: No threads available161 unmodified lines167 168 def __ne__(self, other):169 return not self.__eq__(other)170 170- if not PY3: # Python 2171+ if not PY3: # Python 2172 iterkeys = MutableMapping.iterkeys173 itervalues = MutableMapping.itervalues174 175 __marker = object()58 unmodified lines234 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 ()240 241 if isinstance(other, HTTPHeaderDict):242 for key, val in other.iteritems():61 unmodified lines304 def items(self):305 return list(self.iteritems())306 307 @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 linesmodified:requests/packages/urllib3/connection.py+25 added-14 removed
1+from __future__ import absolute_import2 import datetime3+import os4 import sys5 import socket6 from socket import error as SocketError, timeout as SocketTimeout7 import warnings8 from .packages import six9 10 try: # 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 module13 except ImportError:11- from httplib import HTTPConnection as _HTTPConnection, HTTPException14+ from httplib import HTTPConnection as _HTTPConnection15+ from httplib import HTTPException # noqa: unused in this module16 13-14-class DummyConnection(object):15- "Used to detect a failed ConnectionCls import."16- pass17-18-17 try: # Compiled with SSL?20- HTTPSConnection = DummyConnection18 import ssl19 BaseSSLError = ssl.SSLError20 except (ImportError, AttributeError): # Platform-specific: No SSL.21 ssl = None35 unmodified lines57 58 RECENT_DATE = datetime.date(2014, 1, 1)59 60 61+class DummyConnection(object):62+ """Used to detect a failed ConnectionCls import."""63+ pass64+65+66 class HTTPConnection(_HTTPConnection, object):67 """68 Based on httplib.HTTPConnection but provides an extra constructor69 backwards-compatibility layer between older and newer Pythons.136 unmodified lines206 207 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)214 215 def connect(self):216 # Add certificate verification217 conn = self._new_conn()46 unmodified lines264 '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)268 268- 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)278 279+ self.is_verified = (resolved_cert_reqs == ssl.CERT_REQUIRED or280+ self.assert_fingerprint is not None)281 282+283 if ssl:284 # Make a copy for testing.285 UnverifiedHTTPSConnection = HTTPSConnection286 HTTPSConnection = VerifiedHTTPSConnection2 unmodified linesmodified:requests/packages/urllib3/connectionpool.py+18 added-16 removed
1+from __future__ import absolute_import2 import errno3 import logging4 import sys5 import warnings4 unmodified lines10 try: # Python 311 from queue import LifoQueue, Empty, Full12 except 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: unused16 17 18 from .exceptions import (19 ClosedPoolError,3 unmodified lines23 HostChangedError,24 LocationValueError,25 MaxRetryError,26 ProxyError,25- ConnectTimeoutError,27 ReadTimeoutError,28 SSLError,29 TimeoutError,30 InsecureRequestWarning,4 unmodified lines35 from .connection import (36 port_by_scheme,37 DummyConnection,38 HTTPConnection, HTTPSConnection, VerifiedHTTPSConnection,38- HTTPException, BaseSSLError, ConnectionError39+ HTTPException, BaseSSLError,40 )41 from .request import RequestMethods42 from .response import HTTPResponse43 10 unmodified lines54 55 _Default = object()56 57 57-## Pool objects58+# Pool objects59 class ConnectionPool(object):60 """61 Base class for all connection pools, such as62 :class:`.HTTPConnectionPool` and :class:`.HTTPSConnectionPool`.5 unmodified lines68 def __init__(self, host, port=None):69 if not host:70 raise LocationValueError("No host specified.")71 71- # httplib doesn't like it when we include brackets in ipv6 addresses72- self.host = host.strip('[]')72+ self.host = host73 self.port = port74 75 def __str__(self):76 return '%s(host=%r, port=%r)' % (type(self).__name__,567 unmodified lines644 raise645 return response646 647 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)654 655 # 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)666 667 return response668 669 149 unmodified linesmodified:requests/packages/urllib3/exceptions.py+11 added-3 removed
1+from __future__ import absolute_import2+# Base Exceptions3 2-## Base Exceptions4 5 class HTTPError(Exception):6 "Base exception used by this module."7 pass8 9+10 class HTTPWarning(Warning):11 "Base warning used by this module."12 pass13 14 13-15 class PoolError(HTTPError):16 "Base exception for errors caused within a pool."17 def __init__(self, pool, message):18 self.pool = pool38 unmodified lines57 #: Renamed to ProtocolError but aliased for backwards compatibility.58 ConnectionError = ProtocolError59 60 60-## Leaf Exceptions61+# Leaf Exceptions62 63 class MaxRetryError(RequestError):64 """Raised when the maximum number of retries is exceeded.65 46 unmodified lines112 class ConnectTimeoutError(TimeoutError):113 "Raised when a socket timeout occurs while connecting to a server"114 pass115 116+117 class NewConnectionError(ConnectTimeoutError, PoolError):118 "Raised when we fail to establish a new connection. Usually ECONNREFUSED."119 pass120 121+122 class EmptyPoolError(PoolError):123 "Raised when a pool runs out of connections and no more are allowed."124 pass125 48 unmodified lines174 "Warned when certain SSL configuration is not available on a platform."175 pass176 177 178+class SNIMissingWarning(HTTPWarning):179+ "Warned when making a HTTPS request without SNI available."180+ pass181+182+183 class ResponseNotChunked(ProtocolError, ValueError):184 "Response needs to be chunked in order to read it as chunks."185 pass186 15 unmodified linesmodified:requests/packages/urllib3/fields.py+1 added
1+from __future__ import absolute_import2 import email.utils3 import mimetypes4 5 from .packages import six173 unmodified linesmodified:requests/packages/urllib3/filepost.py+1 added
1+from __future__ import absolute_import2 import codecs3 4 from uuid import uuid45 from io import BytesIO89 unmodified linesmodified:requests/packages/urllib3/poolmanager.py+2 added-1 removed
1+from __future__ import absolute_import2 import logging3 4 try: # Python 35 from urllib.parse import urljoin19 unmodified lines25 26 log = logging.getLogger(__name__)27 28 SSL_KEYWORDS = ('key_file', 'cert_file', 'cert_reqs', 'ca_certs',28- 'ssl_version')29+ 'ssl_version', 'ca_cert_dir')30 31 32 class PoolManager(RequestMethods):33 """248 unmodified linesmodified:requests/packages/urllib3/request.py+3 added-1 removed
1+from __future__ import absolute_import2 try:3 from urllib.parse import urlencode4 except ImportError:5 from urllib import urlencode127 unmodified lines133 extra_kw = {'headers': {}}134 135 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.")139 140 if encode_multipart:141 body, content_type = encode_multipart_formdata(fields, boundary=multipart_boundary)142 else:9 unmodified linesmodified:requests/packages/urllib3/response.py+41 added-12 removed
1+from __future__ import absolute_import2 from contextlib import contextmanager3 import zlib4 import io5 from socket import timeout as SocketTimeout6+from socket import error as SocketError7 8 from ._collections import HTTPHeaderDict9 from .exceptions import (10 ProtocolError, DecodeError, ReadTimeoutError, ResponseNotChunked120 unmodified lines131 encodings = (enc.strip() for enc in tr_enc.split(","))132 if "chunked" in encodings:133 self.chunked = True134 133- # 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)138 139 def get_redirect_location(self):140 """54 unmodified lines195 raise DecodeError(196 "Received response with content-encoding: %s, but "197 "failed to decode it." % content_encoding, e)198 197- 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()201 202 return data203 204+ 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()212+213+ return b''214+215 @contextmanager216 def _error_catcher(self):217 """218 Catch low-level python exceptions, instead re-raising urllib319 unmodified lines238 raise239 240 raise ReadTimeoutError(self._pool, None, 'Read timed out.')241 230- except HTTPException as e:242+ except (HTTPException, SocketError) as e:243 # This includes IncompleteRead.244 raise ProtocolError('Connection broken: %r' % e, e)245+246 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()251 252+ # 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()257+258 raise259 finally:260 if self._original_response and self._original_response.isclosed():261 self.release_conn()57 unmodified lines319 self._body = data320 321 return data322 304-323 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 the30 unmodified lines357 """358 headers = r.msg359 360 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)365 366 # HTTPResponse objects in Python 3 don't have a .strict attribute367 strict = getattr(r, 'strict', 0)103 unmodified lines471 """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.")478 479 # 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 lines486 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 decoded494 495+ 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 decoded502+503 # Chunk content ends with \r\n: discard it.504 while True:505 line = self._fp.fp.readline()506 if not line:8 unmodified linesmodified:requests/__init__.py+3 added-3 removed
40 unmodified lines41 42 """43 44 __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'50 51 # Attempt to enable urllib3's SNI support, if possible52 try:53 from .packages.urllib3.contrib import pyopenssl30 unmodified linesmodified:requests/adapters.py+2 added-2 removed
63 unmodified lines64 covers.65 66 :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 under34 unmodified lines107 self.__attrs__)108 109 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 = {}114 115 for attr, value in state.items():338 unmodified linesmodified:requests/api.py+1 added-1 removed
31 unmodified lines32 :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.Response105 unmodified linesmodified:requests/auth.py+19 added-1 removed
45 unmodified lines46 def __init__(self, username, password):47 self.username = username48 self.password = password49 50+ def __eq__(self, other):51+ return all([52+ self.username == getattr(other, 'username', None),53+ self.password == getattr(other, 'password', None)54+ ])55+56+ def __ne__(self, other):57+ return not self == other58+59 def __call__(self, r):60 r.headers['Authorization'] = _basic_auth_str(self.username, self.password)61 return r62 81 unmodified lines144 cnonce = (hashlib.sha1(s).hexdigest()[:16])145 if _algorithm == 'MD5-SESS':146 HA1 = hash_utf8('%s:%s:%s' % (HA1, nonce, cnonce))147 139- 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', HA276 unmodified lines229 r.register_hook('response', self.handle_redirect)230 self._thread_local.num_401_calls = 1231 232 return r233+234+ def __eq__(self, other):235+ return all([236+ self.username == getattr(other, 'username', None),237+ self.password == getattr(other, 'password', None)238+ ])239+240+ def __ne__(self, other):241+ return not self == othermodified:requests/cookies.py+5 added-3 removed
6 unmodified lines7 """8 9 import copy10 import time11+import calendar12 import collections13 from .compat import cookielib, urlparse, urlunparse, Morsel14 15 try:352 unmodified lines368 if jar is None:369 return None370 371 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 lines424 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 linesmodified:requests/models.py+7 added-4 removed
79 unmodified lines80 if parameters are supplied as a dict.81 """82 83 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 lines323 324 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 lines384 query = query.encode('utf-8')385 if isinstance(fragment, str):386 fragment = fragment.encode('utf-8')387 388+ if isinstance(params, (str, bytes)):389+ params = to_native_string(params)390+391 enc_params = self._encode_params(params)392 if enc_params:393 if query:394 query = '%s&%s' % (query, enc_params)41 unmodified lines436 437 if files:438 raise NotImplementedError('Streamed bodies and files are mutually exclusive.')439 437- 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 lines633 return ('location' in self.headers and self.status_code in REDIRECT_STATI)634 635 @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))639 640 @property641 def apparent_encoding(self):210 unmodified linesmodified:requests/sessions.py+15 added-13 removed
108 unmodified lines109 except (ChunkedEncodingError, ContentDecodingError, RuntimeError):110 resp.raw.read(decode_content=False)111 112 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)114 115 # Release the connection back into the pool.116 resp.close()117 206 unmodified lines324 #: Maximum number of redirects allowed. If the request exceeds this325 #: limit, a :class:`TooManyRedirects` exception is raised.326 self.max_redirects = DEFAULT_REDIRECT_LIMIT327 328- #: Trust environement settings for proxy configuration, default328+ #: Trust environment settings for proxy configuration, default329 #: authentication and similar.330 self.trust_env = True331 332 #: A CookieJar containing all currently outstanding cookies set on this99 unmodified lines432 :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 lines552 # Guard against that specific failure case.553 if not isinstance(request, PreparedRequest):554 raise ValueError('You can only send PreparedRequests.')555 556- 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_url563-556 # 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.hooks560 561+ # 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_url570+571 # Get the appropriate adapter to use572 adapter = self.get_adapter(url=request.url)573 574 # Start time (approximately) of the request60 unmodified lines635 return {'verify': verify, 'proxies': proxies, 'stream': stream,636 'cert': cert}637 638 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():641 642 if url.lower().startswith(prefix):643 return adapter39 unmodified linesmodified:requests/utils.py+6 added-2 removed
113 unmodified lines114 return115 116 ri = urlparse(url)117 118- # 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]124 125 try:126 _netrc = netrc(netrc_path).authenticators(host)127 if _netrc:594 unmodified linesadded:tests/__init__.py+1 added
1+# coding: utf-8added:tests/compat.py+20 added
1+# coding: utf-82+from requests.compat import is_py33+4+5+try:6+ import StringIO7+except ImportError:8+ import io as StringIO9+10+try:11+ from cStringIO import StringIO as cStringIO12+except ImportError:13+ cStringIO = None14+15+if is_py3:16+ def u(s):17+ return s18+else:19+ def u(s):20+ return s.decode('unicode-escape')added:tests/conftest.py+23 added
1+# coding: utf-82+import pytest3+from requests.compat import urljoin4+5+6+def prepare_url(value):7+ # Issue #1483: Make sure the URL always has a trailing slash8+ httpbin_url = value.url.rstrip('/') + '/'9+10+ def inner(*suffix):11+ return urljoin(httpbin_url, '/'.join(suffix))12+13+ return inner14+15+16+@pytest.fixture17+def httpbin(httpbin):18+ return prepare_url(httpbin)19+20+21+@pytest.fixture22+def 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 -*-3+4+"""Tests for Requests."""5+6+from __future__ import division7+import json8+import os9+import pickle10+import collections11+import contextlib12+13+import io14+import requests15+import pytest16+from requests.adapters import HTTPAdapter17+from requests.auth import HTTPDigestAuth, _basic_auth_str18+from requests.compat import (19+ Morsel, cookielib, getproxies, str, urlparse,20+ builtin_str, OrderedDict)21+from requests.cookies import cookiejar_from_dict, morsel_to_cookie22+from requests.exceptions import (23+ ConnectionError, ConnectTimeout, InvalidSchema, InvalidURL,24+ MissingSchema, ReadTimeout, Timeout, RetryError, TooManyRedirects)25+from requests.models import PreparedRequest26+from requests.structures import CaseInsensitiveDict27+from requests.sessions import SessionRedirectMixin28+from requests.models import urlencode29+from requests.hooks import default_hooks30+from .compat import StringIO, u31+32+# Requests to this URL should always fail with a connection timeout (nothing33+# listening on that port)34+TARPIT = 'http://10.255.255.1'35+36+37+class TestRequests:38+39+ def test_entry_points(self):40+41+ requests.session42+ requests.session().get43+ requests.session().head44+ requests.get45+ requests.head46+ requests.put47+ requests.patch48+ requests.post49+50+ @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)61+62+ def test_basic_building(self):63+ req = requests.Request()64+ req.url = 'http://kennethreitz.org/'65+ req.data = {'life': '42'}66+67+ pr = req.prepare()68+ assert pr.url == req.url69+ assert pr.body == 'life=42'70+71+ @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.headers75+76+ 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'83+84+ def test_path_is_not_double_encoded(self):85+ request = requests.Request('GET', "http://0.0.0.0/get/test case").prepare()86+87+ assert request.path_url == '/get/test%20case'88+89+ @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 == expected97+98+ 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'104+105+ 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'109+110+ 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)114+115+ @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)124+125+ def test_HTTP_200_OK_GET_ALTERNATIVE(self, httpbin):126+ r = requests.Request('GET', httpbin('get'))127+ s = requests.Session()128+ s.proxies = getproxies()129+130+ r = s.send(r.prepare())131+132+ assert r.status_code == 200133+134+ 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_redirect139+140+ 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')150+151+ 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')163+164+ # 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)167+168+ def test_HTTP_200_OK_GET_WITH_PARAMS(self, httpbin):169+ heads = {'User-agent': 'Mozilla/5.0'}170+171+ r = requests.get(httpbin('user-agent'), headers=heads)172+173+ assert heads['User-agent'] in r.text174+ assert r.status_code == 200175+176+ def test_HTTP_200_OK_GET_WITH_MIXED_PARAMS(self, httpbin):177+ heads = {'User-agent': 'Mozilla/5.0'}178+179+ r = requests.get(httpbin('get') + '?test=true', params={'q': 'test'}, headers=heads)180+ assert r.status_code == 200181+182+ 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'187+188+ 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']193+194+ 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.cookies206+207+ 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"'211+212+ 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']217+218+ 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'225+226+ 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.cookies231+232+ 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 cj242+243+ 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'250+251+ 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_urls256+257+ 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)264+265+ 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.headers272+273+ @pytest.mark.parametrize('key', ('User-agent', 'user-agent'))274+ def test_user_agent_transfers(self, httpbin, key):275+276+ heads = {key: 'Mozilla/5.0 (github.com/kennethreitz/requests)'}277+278+ r = requests.get(httpbin('user-agent'), headers=heads)279+ assert heads[key] in r.text280+281+ def test_HTTP_200_OK_HEAD(self, httpbin):282+ r = requests.head(httpbin('get'))283+ assert r.status_code == 200284+285+ def test_HTTP_200_OK_PUT(self, httpbin):286+ r = requests.put(httpbin('put'))287+ assert r.status_code == 200288+289+ def test_BASICAUTH_TUPLE_HTTP_200_OK_GET(self, httpbin):290+ auth = ('user', 'pass')291+ url = httpbin('basic-auth', 'user', 'pass')292+293+ r = requests.get(url, auth=auth)294+ assert r.status_code == 200295+296+ r = requests.get(url)297+ assert r.status_code == 401298+299+ s = requests.session()300+ s.auth = auth301+ r = s.get(url)302+ assert r.status_code == 200303+304+ @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)316+317+ def test_basicauth_with_netrc(self, httpbin):318+ auth = ('user', 'pass')319+ wrong_auth = ('wronguser', 'wrongpass')320+ url = httpbin('basic-auth', 'user', 'pass')321+322+ old_auth = requests.sessions.get_netrc_auth323+324+ try:325+ def get_netrc_auth_mock(url):326+ return auth327+ requests.sessions.get_netrc_auth = get_netrc_auth_mock328+329+ # Should use netrc and work.330+ r = requests.get(url)331+ assert r.status_code == 200332+333+ # Given auth should override and fail.334+ r = requests.get(url, auth=wrong_auth)335+ assert r.status_code == 401336+337+ s = requests.session()338+339+ # Should use netrc and work.340+ r = s.get(url)341+ assert r.status_code == 200342+343+ # 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_auth349+350+ def test_DIGEST_HTTP_200_OK_GET(self, httpbin):351+352+ auth = HTTPDigestAuth('user', 'pass')353+ url = httpbin('digest-auth', 'auth', 'user', 'pass')354+355+ r = requests.get(url, auth=auth)356+ assert r.status_code == 200357+358+ r = requests.get(url)359+ assert r.status_code == 401360+361+ s = requests.session()362+ s.auth = HTTPDigestAuth('user', 'pass')363+ r = s.get(url)364+ assert r.status_code == 200365+366+ 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'371+372+ r = requests.get(url, auth=auth)373+ assert r.status_code == 200374+375+ 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'381+382+ def test_DIGEST_STREAM(self, httpbin):383+384+ auth = HTTPDigestAuth('user', 'pass')385+ url = httpbin('digest-auth', 'auth', 'user', 'pass')386+387+ r = requests.get(url, auth=auth, stream=True)388+ assert r.raw.read() != b''389+390+ r = requests.get(url, auth=auth, stream=False)391+ assert r.raw.read() == b''392+393+ def test_DIGESTAUTH_WRONG_HTTP_401_GET(self, httpbin):394+395+ auth = HTTPDigestAuth('user', 'wrongpass')396+ url = httpbin('digest-auth', 'auth', 'user', 'pass')397+398+ r = requests.get(url, auth=auth)399+ assert r.status_code == 401400+401+ r = requests.get(url)402+ assert r.status_code == 401403+404+ s = requests.session()405+ s.auth = auth406+ r = s.get(url)407+ assert r.status_code == 401408+409+ def test_DIGESTAUTH_QUOTES_QOP_VALUE(self, httpbin):410+411+ auth = HTTPDigestAuth('user', 'pass')412+ url = httpbin('digest-auth', 'auth', 'user', 'pass')413+414+ r = requests.get(url, auth=auth)415+ assert '"auth"' in r.request.headers['Authorization']416+417+ def test_POSTBIN_GET_POST_FILES(self, httpbin):418+419+ url = httpbin('post')420+ requests.post(url).raise_for_status()421+422+ post1 = requests.post(url, data={'some': 'data'})423+ assert post1.status_code == 200424+425+ with open('requirements.txt') as f:426+ post2 = requests.post(url, files={'some': f})427+ assert post2.status_code == 200428+429+ post4 = requests.post(url, data='[{"some": "json"}]')430+ assert post4.status_code == 200431+432+ with pytest.raises(ValueError):433+ requests.post(url, files=['bad file data'])434+435+ def test_POSTBIN_GET_POST_FILES_WITH_DATA(self, httpbin):436+437+ url = httpbin('post')438+ requests.post(url).raise_for_status()439+440+ post1 = requests.post(url, data={'some': 'data'})441+ assert post1.status_code == 200442+443+ with open('requirements.txt') as f:444+ post2 = requests.post(url,445+ data={'some': 'data'}, files={'some': f})446+ assert post2.status_code == 200447+448+ post4 = requests.post(url, data='[{"some": "json"}]')449+ assert post4.status_code == 200450+451+ with pytest.raises(ValueError):452+ requests.post(url, files=['bad file data'])453+454+ 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})")459+460+ def test_request_ok_set(self, httpbin):461+ r = requests.get(httpbin('status', '404'))462+ assert not r.ok463+464+ 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()468+469+ r = requests.get(httpbin('status', '500'))470+ assert not r.ok471+472+ def test_decompress_gzip(self, httpbin):473+ r = requests.get(httpbin('gzip'))474+ r.content.decode('ascii')475+476+ @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)486+487+ 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.492+493+ def test_pyopenssl_redirect(self, httpbin_secure, httpbin_ca_bundle):494+ requests.get(httpbin_secure('status', '301'), verify=httpbin_ca_bundle)495+496+ def test_urlencoded_get_query_multivalued_param(self, httpbin):497+498+ 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')501+502+ 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 == 200508+509+ @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 == 200521+522+ 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.body531+532+ 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 == 200537+538+ 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'545+546+ resp = s.send(prep)547+ assert resp.status_code == 200548+549+ 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.body559+560+ def test_hook_receives_request_arguments(self, httpbin):561+ def hook(resp, **kwargs):562+ assert resp is not None563+ assert kwargs != {}564+565+ s = requests.Session()566+ r = requests.Request('GET', httpbin(), hooks={'response': hook})567+ prep = s.prepare_request(r)568+ s.send(prep)569+570+ 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]578+579+ 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]588+589+ def test_prepared_request_hook(self, httpbin):590+ def hook(resp, **kwargs):591+ resp.hook_working = True592+ return resp593+594+ req = requests.Request('GET', httpbin(), hooks={'response': hook})595+ prep = req.prepare()596+597+ s = requests.Session()598+ s.proxies = getproxies()599+ resp = s.send(prep)600+601+ assert hasattr(resp, 'hook_working')602+603+ 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 r608+609+ req = requests.Request('GET', httpbin('headers'))610+ assert not req.auth611+612+ s = requests.Session()613+ s.auth = DummyAuth()614+615+ prep = s.prepare_request(req)616+ resp = s.send(prep)617+618+ assert resp.json()['headers'][619+ 'Dummy-Auth-Test'] == 'dummy-auth-test-ok'620+621+ 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/"626+627+ 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'650+651+ def test_cookie_parameters(self):652+ key = 'some_cookie'653+ value = 'some_value'654+ secure = True655+ domain = 'test.com'656+ rest = {'HttpOnly': True}657+658+ jar = requests.cookies.RequestsCookieJar()659+ jar.set(key, value, secure=secure, domain=domain, rest=rest)660+661+ assert len(jar) == 1662+ assert 'some_cookie' in jar663+664+ cookie = list(jar)[0]665+ assert cookie.secure == secure666+ assert cookie.domain == domain667+ assert cookie._rest['HttpOnly'] == rest['HttpOnly']668+669+ def test_cookie_as_dict_keeps_len(self):670+ key = 'some_cookie'671+ value = 'some_value'672+673+ key1 = 'some_cookie1'674+ value1 = 'some_value1'675+676+ jar = requests.cookies.RequestsCookieJar()677+ jar.set(key, value)678+ jar.set(key1, value1)679+680+ d1 = dict(jar)681+ d2 = dict(jar.iteritems())682+ d3 = dict(jar.items())683+684+ assert len(jar) == 2685+ assert len(d1) == 2686+ assert len(d2) == 2687+ assert len(d3) == 2688+689+ def test_cookie_as_dict_keeps_items(self):690+ key = 'some_cookie'691+ value = 'some_value'692+693+ key1 = 'some_cookie1'694+ value1 = 'some_value1'695+696+ jar = requests.cookies.RequestsCookieJar()697+ jar.set(key, value)698+ jar.set(key1, value1)699+700+ d1 = dict(jar)701+ d2 = dict(jar.iteritems())702+ d3 = dict(jar.items())703+704+ assert d1['some_cookie'] == 'some_value'705+ assert d2['some_cookie'] == 'some_value'706+ assert d3['some_cookie1'] == 'some_value1'707+708+ def test_cookie_as_dict_keys(self):709+ key = 'some_cookie'710+ value = 'some_value'711+712+ key1 = 'some_cookie1'713+ value1 = 'some_value1'714+715+ jar = requests.cookies.RequestsCookieJar()716+ jar.set(key, value)717+ jar.set(key1, value1)718+719+ keys = jar.keys()720+ assert keys == list(keys)721+ # make sure one can use keys multiple times722+ assert list(keys) == list(keys)723+724+ def test_cookie_as_dict_values(self):725+ key = 'some_cookie'726+ value = 'some_value'727+728+ key1 = 'some_cookie1'729+ value1 = 'some_value1'730+731+ jar = requests.cookies.RequestsCookieJar()732+ jar.set(key, value)733+ jar.set(key1, value1)734+735+ values = jar.values()736+ assert values == list(values)737+ # make sure one can use values multiple times738+ assert list(values) == list(values)739+740+ def test_cookie_as_dict_items(self):741+ key = 'some_cookie'742+ value = 'some_value'743+744+ key1 = 'some_cookie1'745+ value1 = 'some_value1'746+747+ jar = requests.cookies.RequestsCookieJar()748+ jar.set(key, value)749+ jar.set(key1, value1)750+751+ items = jar.items()752+ assert items == list(items)753+ # make sure one can use items multiple times754+ assert list(items) == list(items)755+756+ 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.0762+763+ def test_response_is_iterable(self):764+ r = requests.Response()765+ io = StringIO.StringIO('abc')766+ read_ = io.read767+768+ 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()774+775+ 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'784+785+ chunks = r.iter_content(decode_unicode=True)786+ assert all(isinstance(chunk, str) for chunk in chunks)787+788+ # 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)794+795+ def test_request_and_response_are_pickleable(self, httpbin):796+ r = requests.get(httpbin('get'))797+798+ # verify we can pickle the original request799+ assert pickle.loads(pickle.dumps(r.request))800+801+ # 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.headers806+807+ def test_cannot_send_unprepared_requests(self, httpbin):808+ r = requests.Request(url=httpbin())809+ with pytest.raises(ValueError):810+ requests.Session().send(r)811+812+ 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 == response821+822+ def test_session_pickling(self, httpbin):823+ r = requests.Request('GET', httpbin('get'))824+ s = requests.Session()825+826+ s = pickle.loads(pickle.dumps(s))827+ s.proxies = getproxies()828+829+ r = s.send(r.prepare())830+ assert r.status_code == 200831+832+ 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'844+845+ 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()851+852+ 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.adapters889+890+ 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.headers896+897+ 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'}902+903+ 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 == url911+912+ 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()916+917+ # 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()921+922+ @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']929+930+ 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()935+936+ assert 'multipart/form-data' in p.headers['Content-Type']937+938+ 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()943+944+ assert p.headers['Content-Length'] == length945+946+ 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.url956+957+ 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', '')965+966+ 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']970+971+ assert h1 == h2972+973+ 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)978+979+ # 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_redirect984+985+ # 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_redirect991+992+ 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 = False996+997+ 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 resp1003+1004+ adapter.build_response = build_response1005+1006+ 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)1011+1012+ 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"1016+1017+ 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 += 11024+1025+ 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']1033+1034+ 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.body1040+1041+ def test_response_iter_lines(self, httpbin):1042+ r = requests.get(httpbin('stream/4'), stream=True)1043+ assert r.status_code == 2001044+1045+ it = r.iter_lines()1046+ next(it)1047+ assert len(list(it)) == 31048+1049+ def test_unconsumed_session_response_closes_connection(self, httpbin):1050+ s = requests.session()1051+1052+ with contextlib.closing(s.get(httpbin('stream/4'), stream=True)) as response:1053+ pass1054+1055+ assert response._content_consumed is False1056+ assert response.raw.closed1057+1058+ @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 == 2001063+1064+ next(r.iter_lines())1065+ assert len(list(r.iter_lines())) == 31066+1067+1068+class TestCaseInsensitiveDict:1069+1070+ @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 cid1080+1081+ def test_docstring_example(self):1082+ cid = CaseInsensitiveDict()1083+ cid['Accept'] = 'application/json'1084+ assert cid['aCCEPT'] == 'application/json'1085+ assert list(cid) == ['Accept']1086+1087+ def test_len(self):1088+ cid = CaseInsensitiveDict({'a': 'a', 'b': 'b'})1089+ cid['A'] = 'a'1090+ assert len(cid) == 21091+1092+ def test_getitem(self):1093+ cid = CaseInsensitiveDict({'Spam': 'blueval'})1094+ assert cid['spam'] == 'blueval'1095+ assert cid['SPAM'] == 'blueval'1096+1097+ 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']1107+1108+ def test_delitem(self):1109+ cid = CaseInsensitiveDict()1110+ cid['Spam'] = 'someval'1111+ del cid['sPam']1112+ assert 'spam' not in cid1113+ assert len(cid) == 01114+1115+ 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 cid1123+1124+ 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'1132+1133+ 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'1143+1144+ def test_update_retains_unchanged(self):1145+ cid = CaseInsensitiveDict({'foo': 'foo', 'bar': 'bar'})1146+ cid.update({'foo': 'newfoo'})1147+ assert cid['bar'] == 'bar'1148+1149+ def test_iter(self):1150+ cid = CaseInsensitiveDict({'Spam': 'spam', 'Eggs': 'eggs'})1151+ keys = frozenset(['Spam', 'Eggs'])1152+ assert frozenset(iter(cid)) == keys1153+1154+ 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()1162+1163+ def test_setdefault(self):1164+ cid = CaseInsensitiveDict({'Spam': 'blueval'})1165+ assert cid.setdefault('spam', 'notblueval') == 'blueval'1166+ assert cid.setdefault('notspam', 'notblueval') == 'notblueval'1167+1168+ 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 == lowerkeyset1176+1177+ 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) == keyset1186+1187+ 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) == keyset1198+1199+ 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_copy1208+1209+1210+class TestMorselToCookieExpires:1211+ """Tests for morsel_to_cookie when morsel contains expires."""1212+1213+ def test_expires_valid_str(self):1214+ """Test case where we convert expires from string time."""1215+1216+ morsel = Morsel()1217+ morsel['expires'] = 'Thu, 01-Jan-1970 00:00:01 GMT'1218+ cookie = morsel_to_cookie(morsel)1219+ assert cookie.expires == 11220+1221+ @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)1232+1233+ def test_expires_none(self):1234+ """Test case where expires is None."""1235+1236+ morsel = Morsel()1237+ morsel['expires'] = None1238+ cookie = morsel_to_cookie(morsel)1239+ assert cookie.expires is None1240+1241+1242+class TestMorselToCookieMaxAge:1243+1244+ """Tests for morsel_to_cookie when morsel contains max-age."""1245+1246+ def test_max_age_valid_int(self):1247+ """Test case where a valid max age in seconds is passed."""1248+1249+ morsel = Morsel()1250+ morsel['max-age'] = 601251+ cookie = morsel_to_cookie(morsel)1252+ assert isinstance(cookie.expires, int)1253+1254+ def test_max_age_invalid_str(self):1255+ """Test case where a invalid max age is passed."""1256+1257+ morsel = Morsel()1258+ morsel['max-age'] = 'woops'1259+ with pytest.raises(TypeError):1260+ morsel_to_cookie(morsel)1261+1262+1263+class TestTimeout:1264+1265+ 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]1270+1271+ @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)1280+1281+ def test_none_timeout(self, httpbin):1282+ """ Check that you can set None as a valid timeout value.1283+1284+ 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 == 2001292+1293+ 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+ pass1299+1300+ 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)1307+1308+ 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+ pass1314+1315+ 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.ok1319+1320+1321+SendCall = collections.namedtuple('SendCall', ('args', 'kwargs'))1322+1323+1324+class 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 = False1331+1332+ def send(self, *args, **kwargs):1333+ self.calls.append(SendCall(args, kwargs))1334+ return self.build_response()1335+1336+ def build_response(self):1337+ request = self.calls[-1].args[0]1338+ r = requests.Response()1339+1340+ try:1341+ r.status_code = int(self.redirects.pop(0))1342+ except IndexError:1343+ r.status_code = 2001344+1345+ r.headers = CaseInsensitiveDict({'Location': '/'})1346+ r.raw = self._build_raw()1347+ r.request = request1348+ return r1349+1350+ def _build_raw(self):1351+ string = StringIO.StringIO('')1352+ setattr(string, 'release_conn', lambda *args: args)1353+ return string1354+1355+1356+def 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_call1375+1376+1377+@pytest.mark.parametrize(1378+ 'data', (1379+ (('a', 'b'), ('c', 'd')),1380+ (('c', 'd'), ('a', 'b')),1381+ (('a', 'b'), ('c', 'd'), ('e', 'f')),1382+ ))1383+def 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)1395+1396+1397+@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+ ))1418+def 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)1425+1426+1427+def 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+ )))1433+1434+ with pytest.raises(RetryError):1435+ s.get(httpbin('status/500'))1436+1437+1438+def test_urllib3_pool_connection_closed(httpbin):1439+ s = requests.Session()1440+ s.mount('http://', HTTPAdapter(pool_connections=0, pool_maxsize=0))1441+1442+ try:1443+ s.get(httpbin('status/200'))1444+ except ConnectionError as e:1445+ assert u"Pool is closed." in str(e)1446+1447+1448+def test_vendor_aliases():1449+ from requests.packages import urllib31450+ from requests.packages import chardet1451+1452+ with pytest.raises(ImportError):1453+ from requests.packages import webbrowser1454+1455+1456+1457+if __name__ == '__main__':1458+ unittest.main()added:tests/test_utils.py+374 added
1+# coding: utf-82+import os3+import threading4+import socket5+import time6+from io import BytesIO7+8+import pytest9+import requests10+from requests import compat11+from 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)17+18+from .compat import StringIO, cStringIO19+20+from testserver.server import Server21+22+23+class TestSuperLen:24+25+ @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)) == 435+36+ 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) == 041+42+43+class TestGetEnvironProxies:44+ """Ensures that IP addresses are correctly matches with ranges45+ in no_proxy variable."""46+47+ @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]52+53+ @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) == {}63+64+ @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) != {}72+73+74+class TestIsIPv4Address:75+76+ def test_valid(self):77+ assert is_ipv4_address('8.8.8.8')78+79+ @pytest.mark.parametrize('value', ('8.8.8.8.8', 'localhost.localdomain'))80+ def test_invalid(self, value):81+ assert not is_ipv4_address(value)82+83+84+class TestIsValidCIDR:85+86+ def test_valid(self):87+ assert is_valid_cidr('192.168.1.0/24')88+89+ @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)99+100+101+class TestAddressInNetwork:102+103+ def test_valid(self):104+ assert address_in_network('192.168.1.1', '192.168.1.0/24')105+106+ def test_invalid(self):107+ assert not address_in_network('172.16.0.1', '192.168.1.0/24')108+109+110+class TestGuessFilename:111+112+ @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 None117+118+ @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)128+129+130+class TestContentEncodingDetection:131+132+ def test_none(self):133+ encodings = get_encodings_from_content('')134+ assert not len(encodings)135+136+ @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'151+152+ 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']159+160+ 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']) 165+166+ 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 block170+171+ assert r.status_code == 200172+ assert r.request.headers['Transfer-Encoding'] == 'chunked'173+174+175+176+177+USER = PASSWORD = "%!*'();:@&=+$,/?#[] "178+ENCODED_USER = compat.quote(USER, '')179+ENCODED_PASSWORD = compat.quote(PASSWORD, '')180+181+182+@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+ ))210+def test_get_auth_from_url(url, auth):211+ assert get_auth_from_url(url) == auth212+213+214+@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+ ))227+def test_requote_uri_with_unquoted_percents(uri, expected):228+ """See: https://github.com/kennethreitz/requests/issues/2356229+ """230+ assert requote_uri(uri) == expected231+232+233+@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+ ))239+def test_dotted_netmask(mask, expected):240+ assert dotted_netmask(mask) == expected241+242+243+@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+ ))249+def 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) == expected254+255+class 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()271+272+ def test_server_closes(self):273+ with Server.basic_response_server() as (host, port):274+ sock = socket.socket()275+ sock.connect((host, port))276+277+ sock.close()278+279+ with pytest.raises(socket.error):280+ new_sock = socket.socket()281+ new_sock.connect((host, port))282+283+ 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+ )289+290+ with server as (host, port):291+ r = requests.get('http://{}:{}'.format(host, port))292+293+ 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'303+304+ def test_basic_waiting_server(self):305+ block_server = threading.Event()306+307+ 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 block314+315+ def test_multiple_requests(self):316+ requests_to_handle = 5317+ 318+ server = Server.basic_response_server(requests_to_handle=requests_to_handle)319+320+ 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 == 200325+326+ # the (n+1)th request fails327+ with pytest.raises(requests.exceptions.ConnectionError):328+ r = requests.get(server_url)329+330+ 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"334+335+ 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()342+343+ sock2.connect(address)344+ sock2.send(second_request.encode())345+ sock2.close()346+347+ assert server.handler_results[0] == first_request348+ assert server.handler_results[1] == second_request349+350+ def test_requests_after_timeout_are_not_received(self):351+ server = Server.basic_response_server(request_timeout=1)352+353+ 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()359+360+ assert server.handler_results[0] == ""361+362+363+ def test_request_recovery_with_bigger_timeout(self):364+ server = Server.basic_response_server(request_timeout=3)365+ data = "bananadine"366+367+ 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] == datamodified:AUTHORS.rst+3 added-1 removed
132 unmodified lines133 - 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 lines161 - 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 line2 3 Release History4 ---------------5 6-dev (XXXX)7-++++++++++6+2.9.2 (???)7++++++++++++8 9+**Bugfixes**10+11+- Don't use redirect_cache if allow_redirects=False12+13+2.9.1 (2015-12-21)14+++++++++++++++++++15+16+**Bugfixes**17+18+- 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.21+22+**Miscellaneous**23+24+- Updated bundled urllib3 to 1.13.1.25+26+2.9.0 (2015-12-15)27+++++++++++++++++++28+29 **Minor Improvements** (Backwards compatible)30 31 - 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.36 37+**Bugfixes**38+39+- 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.56+57+**Miscellaneous**58+59+- Updated urllib3 to 1.13.60+61 2.8.1 (2015-10-13)62 ++++++++++++++++++63 64 **Bugfixes**31 unmodified lines96 97 - 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 lines579 580 - 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 posts585 586 587 0.14.1 (2012-10-01)78 unmodified lines666 0.13.0 (2012-05-29)667 +++++++++++++++++++668 669 - 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 linesmodified:LICENSE+1 added-1 removed
1-Copyright 2015 Kenneth Reitz1+Copyright 2016 Kenneth Reitz2 3 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 at8 unmodified linesmodified:Makefile+4 added-3 removed
4 unmodified lines5 6 test: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 tests10 11 coverage:12- py.test --verbose --cov-report term --cov=requests test_requests.py12+ py.test --verbose --cov-report term --cov=requests tests13 14 ci: init15 py.test --junitxml=junit.xml16 10 unmodified lines27 28 publish: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-info33 34 35 docs-init:36 pip install -r docs/requirements.txt4 unmodified linesmodified:README.rst+38 added-27 removed
5 unmodified lines6 7 .. image:: https://img.shields.io/pypi/dm/requests.svg8 :target: https://pypi.python.org/pypi/requests9 10+Requests is the only *Non-GMO* HTTP library for Python, safe for human11+consumption.12 13+**Warning:** Recreational use of other HTTP libraries may result in dangerous side-effects,14+including: security vulnerabilities, verbose code, reinventing the wheel,15+constantly reading documentation, depression, headaches, or even death.16 17+Behold, the power of Requests:18 13-Requests is an Apache2 Licensed HTTP library, written in Python, for human14-beings.15-16-Most existing Python modules for sending HTTP requests are extremely17-verbose and cumbersome. Python's builtin urllib2 module provides most of18-the HTTP capabilities you should need, but the api is thoroughly broken.19-It requires an enormous amount of work (even method overrides) to20-perform the simplest of tasks.21-22-Things shouldn't be this way. Not in Python.23-19 .. code-block:: python20 26- >>> 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, ...}32 34-See `the same code, without Requests <https://gist.github.com/973705>`_.33+See `the similar code, sans Requests <https://gist.github.com/973705>`_.34 36-Requests allow you to send HTTP/1.1 requests. You can add headers, form data,37-multipart files, and parameters with simple Python dictionaries, and access the38-response 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 crazy40-hacks for you.35+Requests allows you to send *organic, grass-fed* HTTP/1.1 requests, without the36+need for manual labor. There's no need to manually add query strings to your37+URLs, or to form-encode your POST data. Keep-alive and HTTP connection pooling38+are 100% automatic, powered by `urllib3 <https://github.com/shazow/urllib3>`_,39+which is embedded within Requests.40 41+Besides, all the cool kids are doing it. Requests is one of the most42+downloaded Python packages of all time, pulling in over 7,000,000 downloads43+every month. You don't want to be left out!44 43-Features44---------45+Feature Support46+---------------47 48+Requests is ready for today's web.49+50 - 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 support66 67+Requests supports Python 2.6 — 3.5, and runs great on PyPy.68 69 Installation70 ------------71 1 unmodified line73 74 .. code-block:: bash75 76 $ pip install requests77+ ✨🍰✨78 79+Satisfaction, guaranteed.80 81 Documentation82 -------------83 73-Documentation is available at http://docs.python-requests.org/.84+Fantastic documentation is available at http://docs.python-requests.org/, for a limited time only.85 86 76-Contribute77-----------87+How to Contribute88+-----------------89 90 #. 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 linesadded:requirements-to-freeze.txt+4 added
1+pytest2+pytest-cov3+pytest-httpbin4+sphinxmodified:requirements.txt+22 added-6 removed
1-py==1.4.302-pytest==2.8.13-pytest-cov==2.1.04-pytest-httpbin==0.0.75-httpbin==0.4.06-wheel1+alabaster==0.7.72+Babel==2.2.03+coverage==4.0.34+decorator==4.0.95+docutils==0.126+Flask==0.10.17+httpbin==0.4.18+itsdangerous==0.249+Jinja2==2.810+MarkupSafe==0.2311+py==1.4.3112+Pygments==2.1.113+pytest==2.8.714+pytest-cov==2.2.115+pytest-httpbin==0.2.016+pytz==2015.717+six==1.10.018+snowballstemmer==1.2.119+Sphinx==1.3.520+sphinx-rtd-theme==0.1.921+Werkzeug==0.11.422+wheel==0.29.0deleted:setup.cfg-2 removed
1-[wheel]2-universal = 1modified:setup.py+28 added-5 removed
4 unmodified lines5 import sys6 7 from codecs import open8 9-try:10- from setuptools import setup11-except ImportError:12- from distutils.core import setup9+from setuptools import setup10+from setuptools.command.test import test as TestCommand11 12+13+class PyTest(TestCommand):14+ user_options = [('pytest-args=', 'a', "Arguments to pass into py.test")]15+16+ def initialize_options(self):17+ TestCommand.initialize_options(self)18+ self.pytest_args = []19+20+ def finalize_options(self):21+ TestCommand.finalize_options(self)22+ self.test_args = []23+ self.test_suite = True24+25+ def run_tests(self):26+ import pytest27+28+ errno = pytest.main(self.pytest_args)29+ sys.exit(errno)30+31+32 if sys.argv[-1] == 'publish':33 os.system('python setup.py sdist upload')34 sys.exit()35 8 unmodified lines44 'requests.packages.urllib3.packages.ssl_match_hostname',45 ]46 47 requires = []48+test_requirements = ['pytest>=2.8.0', 'pytest-httpbin==0.0.7', 'pytest-cov']49 31-version = ''50 with 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 lines79 '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 -*-3-4-"""Tests for Requests."""5-6-from __future__ import division7-import json8-import os9-import pickle10-import unittest11-import collections12-import contextlib13-14-import io15-import requests16-import pytest17-from requests.adapters import HTTPAdapter18-from requests.auth import HTTPDigestAuth, _basic_auth_str19-from requests.compat import (20- Morsel, cookielib, getproxies, str, urljoin, urlparse, is_py3,21- builtin_str, OrderedDict22- )23-from requests.cookies import cookiejar_from_dict, morsel_to_cookie24-from requests.exceptions import (ConnectionError, ConnectTimeout,25- InvalidSchema, InvalidURL, MissingSchema,26- ReadTimeout, Timeout, RetryError)27-from requests.models import PreparedRequest28-from requests.structures import CaseInsensitiveDict29-from requests.sessions import SessionRedirectMixin30-from requests.models import urlencode31-from requests.hooks import default_hooks32-from testserver.server import Server33-import socket34-import threading35-import time36-37-try:38- import StringIO39-except ImportError:40- import io as StringIO41-42-try:43- from multiprocessing.pool import ThreadPool44-except ImportError:45- ThreadPool = None46-47-if is_py3:48- def u(s):49- return s50-else:51- def u(s):52- return s.decode('unicode-escape')53-54-55-@pytest.fixture56-def httpbin(httpbin):57- # Issue #1483: Make sure the URL always has a trailing slash58- httpbin_url = httpbin.url.rstrip('/') + '/'59-60- def inner(*suffix):61- return urljoin(httpbin_url, '/'.join(suffix))62-63- return inner64-65-66-@pytest.fixture67-def httpsbin_url(httpbin_secure):68- # Issue #1483: Make sure the URL always has a trailing slash69- httpbin_url = httpbin_secure.url.rstrip('/') + '/'70-71- def inner(*suffix):72- return urljoin(httpbin_url, '/'.join(suffix))73-74- return inner75-76-77-# Requests to this URL should always fail with a connection timeout (nothing78-# listening on that port)79-TARPIT = "http://10.255.255.1"80-81-class TestRequests(object):82-83- _multiprocess_can_split_ = True84-85- def setUp(self):86- """Create simple data set with headers."""87- pass88-89- def tearDown(self):90- """Teardown."""91- pass92-93- def test_entry_points(self):94-95- requests.session96- requests.session().get97- requests.session().head98- requests.get99- requests.head100- requests.put101- requests.patch102- requests.post103-104- 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://')115-116- def test_basic_building(self):117- req = requests.Request()118- req.url = 'http://kennethreitz.org/'119- req.data = {'life': '42'}120-121- pr = req.prepare()122- assert pr.url == req.url123- assert pr.body == 'life=42'124-125- 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.headers130-131- 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'138-139- def test_path_is_not_double_encoded(self):140- request = requests.Request('GET', "http://0.0.0.0/get/test case").prepare()141-142- assert request.path_url == '/get/test%20case'143-144- 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"151-152- 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'158-159- 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'163-164- 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)174-175- def test_HTTP_200_OK_GET_ALTERNATIVE(self, httpbin):176- r = requests.Request('GET', httpbin('get'))177- s = requests.Session()178- s.proxies = getproxies()179-180- r = s.send(r.prepare())181-182- assert r.status_code == 200183-184- 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_redirect189-190- # 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)193-194- def test_HTTP_200_OK_GET_WITH_PARAMS(self, httpbin):195- heads = {'User-agent': 'Mozilla/5.0'}196-197- r = requests.get(httpbin('user-agent'), headers=heads)198-199- assert heads['User-agent'] in r.text200- assert r.status_code == 200201-202- def test_HTTP_200_OK_GET_WITH_MIXED_PARAMS(self, httpbin):203- heads = {'User-agent': 'Mozilla/5.0'}204-205- r = requests.get(httpbin('get') + '?test=true', params={'q': 'test'}, headers=heads)206- assert r.status_code == 200207-208- 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'213-214- 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']219-220- 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.cookies232-233- 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"'237-238- 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']243-244- 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'251-252- 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.cookies257-258- 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 cj268-269- 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'276-277- 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_urls282-283- 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)292-293- 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.headers300-301- def test_user_agent_transfers(self, httpbin):302-303- heads = {304- 'User-agent': 'Mozilla/5.0 (github.com/kennethreitz/requests)'305- }306-307- r = requests.get(httpbin('user-agent'), headers=heads)308- assert heads['User-agent'] in r.text309-310- heads = {311- 'user-agent': 'Mozilla/5.0 (github.com/kennethreitz/requests)'312- }313-314- r = requests.get(httpbin('user-agent'), headers=heads)315- assert heads['user-agent'] in r.text316-317- def test_HTTP_200_OK_HEAD(self, httpbin):318- r = requests.head(httpbin('get'))319- assert r.status_code == 200320-321- def test_HTTP_200_OK_PUT(self, httpbin):322- r = requests.put(httpbin('put'))323- assert r.status_code == 200324-325- def test_BASICAUTH_TUPLE_HTTP_200_OK_GET(self, httpbin):326- auth = ('user', 'pass')327- url = httpbin('basic-auth', 'user', 'pass')328-329- r = requests.get(url, auth=auth)330- assert r.status_code == 200331-332- r = requests.get(url)333- assert r.status_code == 401334-335- s = requests.session()336- s.auth = auth337- r = s.get(url)338- assert r.status_code == 200339-340- 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")344-345- 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)349-350- 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")354-355- def test_basicauth_with_netrc(self, httpbin):356- auth = ('user', 'pass')357- wrong_auth = ('wronguser', 'wrongpass')358- url = httpbin('basic-auth', 'user', 'pass')359-360- old_auth = requests.sessions.get_netrc_auth361-362- try:363- def get_netrc_auth_mock(url):364- return auth365- requests.sessions.get_netrc_auth = get_netrc_auth_mock366-367- # Should use netrc and work.368- r = requests.get(url)369- assert r.status_code == 200370-371- # Given auth should override and fail.372- r = requests.get(url, auth=wrong_auth)373- assert r.status_code == 401374-375- s = requests.session()376-377- # Should use netrc and work.378- r = s.get(url)379- assert r.status_code == 200380-381- # 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_auth387-388- def test_DIGEST_HTTP_200_OK_GET(self, httpbin):389-390- auth = HTTPDigestAuth('user', 'pass')391- url = httpbin('digest-auth', 'auth', 'user', 'pass')392-393- r = requests.get(url, auth=auth)394- assert r.status_code == 200395-396- r = requests.get(url)397- assert r.status_code == 401398-399- s = requests.session()400- s.auth = HTTPDigestAuth('user', 'pass')401- r = s.get(url)402- assert r.status_code == 200403-404- 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'409-410- r = requests.get(url, auth=auth)411- assert r.status_code == 200412-413- 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'419-420- def test_DIGEST_STREAM(self, httpbin):421-422- auth = HTTPDigestAuth('user', 'pass')423- url = httpbin('digest-auth', 'auth', 'user', 'pass')424-425- r = requests.get(url, auth=auth, stream=True)426- assert r.raw.read() != b''427-428- r = requests.get(url, auth=auth, stream=False)429- assert r.raw.read() == b''430-431- def test_DIGESTAUTH_WRONG_HTTP_401_GET(self, httpbin):432-433- auth = HTTPDigestAuth('user', 'wrongpass')434- url = httpbin('digest-auth', 'auth', 'user', 'pass')435-436- r = requests.get(url, auth=auth)437- assert r.status_code == 401438-439- r = requests.get(url)440- assert r.status_code == 401441-442- s = requests.session()443- s.auth = auth444- r = s.get(url)445- assert r.status_code == 401446-447- def test_DIGESTAUTH_QUOTES_QOP_VALUE(self, httpbin):448-449- auth = HTTPDigestAuth('user', 'pass')450- url = httpbin('digest-auth', 'auth', 'user', 'pass')451-452- r = requests.get(url, auth=auth)453- assert '"auth"' in r.request.headers['Authorization']454-455- def test_POSTBIN_GET_POST_FILES(self, httpbin):456-457- url = httpbin('post')458- post1 = requests.post(url).raise_for_status()459-460- post1 = requests.post(url, data={'some': 'data'})461- assert post1.status_code == 200462-463- with open('requirements.txt') as f:464- post2 = requests.post(url, files={'some': f})465- assert post2.status_code == 200466-467- post4 = requests.post(url, data='[{"some": "json"}]')468- assert post4.status_code == 200469-470- with pytest.raises(ValueError):471- requests.post(url, files=['bad file data'])472-473- def test_POSTBIN_GET_POST_FILES_WITH_DATA(self, httpbin):474-475- url = httpbin('post')476- post1 = requests.post(url).raise_for_status()477-478- post1 = requests.post(url, data={'some': 'data'})479- assert post1.status_code == 200480-481- with open('requirements.txt') as f:482- post2 = requests.post(url,483- data={'some': 'data'}, files={'some': f})484- assert post2.status_code == 200485-486- post4 = requests.post(url, data='[{"some": "json"}]')487- assert post4.status_code == 200488-489- with pytest.raises(ValueError):490- requests.post(url, files=['bad file data'])491-492- 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})")497-498- def test_request_ok_set(self, httpbin):499- r = requests.get(httpbin('status', '404'))500- assert not r.ok501-502- 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()506-507- r = requests.get(httpbin('status', '500'))508- assert not r.ok509-510- def test_decompress_gzip(self, httpbin):511- r = requests.get(httpbin('gzip'))512- r.content.decode('ascii')513-514- 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'})521-522- 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.527-528- def test_pyopenssl_redirect(self, httpsbin_url, httpbin_ca_bundle):529- requests.get(httpsbin_url('status', '301'), verify=httpbin_ca_bundle)530-531- def test_urlencoded_get_query_multivalued_param(self, httpbin):532-533- 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')536-537- 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 == 200543-544- 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 == 200549-550- 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 == 200554-555- r = requests.post(httpbin('post'),556- data={'stuff': 'elixr'},557- files={'file': ('test_requests.py', open(__file__, 'rb'))})558- assert r.status_code == 200559-560- 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 == 200564-565- 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.body575-576- 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 == 200581-582- 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"589-590- resp = s.send(prep)591- assert resp.status_code == 200592-593- 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.body602-603- def test_hook_receives_request_arguments(self, httpbin):604- def hook(resp, **kwargs):605- assert resp is not None606- assert kwargs != {}607-608- requests.Request('GET', httpbin(), hooks={'response': hook})609-610- 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]618-619- 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]628-629- def test_prepared_request_hook(self, httpbin):630- def hook(resp, **kwargs):631- resp.hook_working = True632- return resp633-634- req = requests.Request('GET', httpbin(), hooks={'response': hook})635- prep = req.prepare()636-637- s = requests.Session()638- s.proxies = getproxies()639- resp = s.send(prep)640-641- assert hasattr(resp, 'hook_working')642-643- 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 r648-649- req = requests.Request('GET', httpbin('headers'))650- assert not req.auth651-652- s = requests.Session()653- s.auth = DummyAuth()654-655- prep = s.prepare_request(req)656- resp = s.send(prep)657-658- assert resp.json()['headers'][659- 'Dummy-Auth-Test'] == 'dummy-auth-test-ok'660-661- 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/"666-667- 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'690-691- def test_cookie_parameters(self):692- key = 'some_cookie'693- value = 'some_value'694- secure = True695- domain = 'test.com'696- rest = {'HttpOnly': True}697-698- jar = requests.cookies.RequestsCookieJar()699- jar.set(key, value, secure=secure, domain=domain, rest=rest)700-701- assert len(jar) == 1702- assert 'some_cookie' in jar703-704- cookie = list(jar)[0]705- assert cookie.secure == secure706- assert cookie.domain == domain707- assert cookie._rest['HttpOnly'] == rest['HttpOnly']708-709- def test_cookie_as_dict_keeps_len(self):710- key = 'some_cookie'711- value = 'some_value'712-713- key1 = 'some_cookie1'714- value1 = 'some_value1'715-716- jar = requests.cookies.RequestsCookieJar()717- jar.set(key, value)718- jar.set(key1, value1)719-720- d1 = dict(jar)721- d2 = dict(jar.iteritems())722- d3 = dict(jar.items())723-724- assert len(jar) == 2725- assert len(d1) == 2726- assert len(d2) == 2727- assert len(d3) == 2728-729- def test_cookie_as_dict_keeps_items(self):730- key = 'some_cookie'731- value = 'some_value'732-733- key1 = 'some_cookie1'734- value1 = 'some_value1'735-736- jar = requests.cookies.RequestsCookieJar()737- jar.set(key, value)738- jar.set(key1, value1)739-740- d1 = dict(jar)741- d2 = dict(jar.iteritems())742- d3 = dict(jar.items())743-744- assert d1['some_cookie'] == 'some_value'745- assert d2['some_cookie'] == 'some_value'746- assert d3['some_cookie1'] == 'some_value1'747-748- def test_cookie_as_dict_keys(self):749- key = 'some_cookie'750- value = 'some_value'751-752- key1 = 'some_cookie1'753- value1 = 'some_value1'754-755- jar = requests.cookies.RequestsCookieJar()756- jar.set(key, value)757- jar.set(key1, value1)758-759- keys = jar.keys()760- assert keys == list(keys)761- # make sure one can use keys multiple times762- assert list(keys) == list(keys)763-764- def test_cookie_as_dict_values(self):765- key = 'some_cookie'766- value = 'some_value'767-768- key1 = 'some_cookie1'769- value1 = 'some_value1'770-771- jar = requests.cookies.RequestsCookieJar()772- jar.set(key, value)773- jar.set(key1, value1)774-775- values = jar.values()776- assert values == list(values)777- # make sure one can use values multiple times778- assert list(values) == list(values)779-780- def test_cookie_as_dict_items(self):781- key = 'some_cookie'782- value = 'some_value'783-784- key1 = 'some_cookie1'785- value1 = 'some_value1'786-787- jar = requests.cookies.RequestsCookieJar()788- jar.set(key, value)789- jar.set(key1, value1)790-791- items = jar.items()792- assert items == list(items)793- # make sure one can use items multiple times794- assert list(items) == list(items)795-796- 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.0802-803- def test_response_is_iterable(self):804- r = requests.Response()805- io = StringIO.StringIO('abc')806- read_ = io.read807-808- 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()814-815- 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'824-825- chunks = r.iter_content(decode_unicode=True)826- assert all(isinstance(chunk, str) for chunk in chunks)827-828- # 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)834-835- def test_request_and_response_are_pickleable(self, httpbin):836- r = requests.get(httpbin('get'))837-838- # verify we can pickle the original request839- assert pickle.loads(pickle.dumps(r.request))840-841- # 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.headers846-847- 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)850-851- 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)854-855- 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)858-859- 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)862-863- 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)866-867- def test_cannot_send_unprepared_requests(self, httpbin):868- r = requests.Request(url=httpbin())869- with pytest.raises(ValueError):870- requests.Session().send(r)871-872- 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 == response881-882- def test_session_pickling(self, httpbin):883- r = requests.Request('GET', httpbin('get'))884- s = requests.Session()885-886- s = pickle.loads(pickle.dumps(s))887- s.proxies = getproxies()888-889- r = s.send(r.prepare())890- assert r.status_code == 200891-892- 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'904-905- 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()911-912- 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.adapters949-950- 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.headers956-957- 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'}962-963- 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 == url971-972- 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()976-977- # 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()981-982- 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()987-988- assert 'multipart/form-data' in p.headers['Content-Type']989-990- 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']1002-1003- 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()1008-1009- assert 'multipart/form-data' in p.headers['Content-Type']1010-1011- 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()1016-1017- assert p.headers['Content-Length'] == length1018-1019- 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.url1029-1030- 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', '')1038-1039- 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']1043-1044- assert h1 == h21045-1046- 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)1051-1052- # 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_redirect1057-1058- # 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_redirect1064-1065- 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 = False1069-1070- 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 resp1076-1077- adapter.build_response = build_response1078-1079- 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)1084-1085- 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"1089-1090- 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 + 11097-1098- 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']1106-1107- 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.body1113-1114- def test_response_iter_lines(self, httpbin):1115- r = requests.get(httpbin('stream/4'), stream=True)1116- assert r.status_code == 2001117-1118- it = r.iter_lines()1119- next(it)1120- assert len(list(it)) == 31121-1122- def test_unconsumed_session_response_closes_connection(self, httpbin):1123- s = requests.session()1124-1125- with contextlib.closing(s.get(httpbin('stream/4'), stream=True)) as response:1126- pass1127-1128- assert response._content_consumed is False1129- assert response.raw.closed1130-1131- @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 == 2001136-1137- next(r.iter_lines())1138- assert len(list(r.iter_lines())) == 31139-1140-1141-class TestContentEncodingDetection(unittest.TestCase):1142-1143- def test_none(self):1144- encodings = requests.utils.get_encodings_from_content('')1145- assert not len(encodings)1146-1147- 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'1153-1154- 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'1160-1161- 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'1167-1168- 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'1174-1175- 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']1183-1184- 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']) 1189-1190- 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 block1194-1195- assert r.status_code == 2001196- assert r.request.headers['Transfer-Encoding'] == 'chunked'1197-1198-class TestCaseInsensitiveDict(unittest.TestCase):1199-1200- def test_mapping_init(self):1201- cid = CaseInsensitiveDict({'Foo': 'foo', 'BAr': 'bar'})1202- assert len(cid) == 21203- assert 'foo' in cid1204- assert 'bar' in cid1205-1206- def test_iterable_init(self):1207- cid = CaseInsensitiveDict([('Foo', 'foo'), ('BAr', 'bar')])1208- assert len(cid) == 21209- assert 'foo' in cid1210- assert 'bar' in cid1211-1212- def test_kwargs_init(self):1213- cid = CaseInsensitiveDict(FOO='foo', BAr='bar')1214- assert len(cid) == 21215- assert 'foo' in cid1216- assert 'bar' in cid1217-1218- def test_docstring_example(self):1219- cid = CaseInsensitiveDict()1220- cid['Accept'] = 'application/json'1221- assert cid['aCCEPT'] == 'application/json'1222- assert list(cid) == ['Accept']1223-1224- def test_len(self):1225- cid = CaseInsensitiveDict({'a': 'a', 'b': 'b'})1226- cid['A'] = 'a'1227- assert len(cid) == 21228-1229- def test_getitem(self):1230- cid = CaseInsensitiveDict({'Spam': 'blueval'})1231- assert cid['spam'] == 'blueval'1232- assert cid['SPAM'] == 'blueval'1233-1234- 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']1244-1245- def test_delitem(self):1246- cid = CaseInsensitiveDict()1247- cid['Spam'] = 'someval'1248- del cid['sPam']1249- assert 'spam' not in cid1250- assert len(cid) == 01251-1252- 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 cid1260-1261- 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'1269-1270- 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'1280-1281- def test_update_retains_unchanged(self):1282- cid = CaseInsensitiveDict({'foo': 'foo', 'bar': 'bar'})1283- cid.update({'foo': 'newfoo'})1284- assert cid['bar'] == 'bar'1285-1286- def test_iter(self):1287- cid = CaseInsensitiveDict({'Spam': 'spam', 'Eggs': 'eggs'})1288- keys = frozenset(['Spam', 'Eggs'])1289- assert frozenset(iter(cid)) == keys1290-1291- 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()1299-1300- def test_setdefault(self):1301- cid = CaseInsensitiveDict({'Spam': 'blueval'})1302- assert cid.setdefault('spam', 'notblueval') == 'blueval'1303- assert cid.setdefault('notspam', 'notblueval') == 'notblueval'1304-1305- 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 == lowerkeyset1313-1314- 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) == keyset1323-1324- 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) == keyset1335-1336- 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_copy1345-1346-1347-class UtilsTestCase(unittest.TestCase):1348-1349- 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_len1354-1355- assert super_len(StringIO.StringIO()) == 01356- assert super_len(1357- StringIO.StringIO('with so much drama in the LBC')) == 291358-1359- assert super_len(BytesIO()) == 01360- assert super_len(1361- BytesIO(b"it's kinda hard bein' snoop d-o-double-g")) == 401362-1363- try:1364- import cStringIO1365- except ImportError:1366- pass1367- else:1368- assert super_len(1369- cStringIO.StringIO('but some how, some way...')) == 251370-1371- 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) == 01377-1378- 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/') != {}1389-1390- 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/') != {}1398-1399- 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 None1407-1408- def test_guess_filename_when_int(self):1409- from requests.utils import guess_filename1410- assert None is guess_filename(1)1411-1412- 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)1416-1417- 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)1424-1425- 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)1433-1434- 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')1439-1440- 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')1444-1445- 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'1450-1451- 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')1455-1456- 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_chars1469-1470- def test_requote_uri_with_unquoted_percents(self):1471- """Ensure we handle unquoted percent signs in redirects.1472-1473- 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)1479-1480- 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)1485-1486-1487-class TestMorselToCookieExpires(unittest.TestCase):1488-1489- """Tests for morsel_to_cookie when morsel contains expires."""1490-1491- def test_expires_valid_str(self):1492- """Test case where we convert expires from string time."""1493-1494- morsel = Morsel()1495- morsel['expires'] = 'Thu, 01-Jan-1970 00:00:01 GMT'1496- cookie = morsel_to_cookie(morsel)1497- assert cookie.expires == 11498-1499- def test_expires_invalid_int(self):1500- """Test case where an invalid type is passed for expires."""1501-1502- morsel = Morsel()1503- morsel['expires'] = 1001504- with pytest.raises(TypeError):1505- morsel_to_cookie(morsel)1506-1507- def test_expires_invalid_str(self):1508- """Test case where an invalid string is input."""1509-1510- morsel = Morsel()1511- morsel['expires'] = 'woops'1512- with pytest.raises(ValueError):1513- morsel_to_cookie(morsel)1514-1515- def test_expires_none(self):1516- """Test case where expires is None."""1517-1518- morsel = Morsel()1519- morsel['expires'] = None1520- cookie = morsel_to_cookie(morsel)1521- assert cookie.expires is None1522-1523-1524-class TestMorselToCookieMaxAge(unittest.TestCase):1525-1526- """Tests for morsel_to_cookie when morsel contains max-age."""1527-1528- def test_max_age_valid_int(self):1529- """Test case where a valid max age in seconds is passed."""1530-1531- morsel = Morsel()1532- morsel['max-age'] = 601533- cookie = morsel_to_cookie(morsel)1534- assert isinstance(cookie.expires, int)1535-1536- def test_max_age_invalid_str(self):1537- """Test case where a invalid max age is passed."""1538-1539- morsel = Morsel()1540- morsel['max-age'] = 'woops'1541- with pytest.raises(TypeError):1542- morsel_to_cookie(morsel)1543-1544-1545-class 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]1551-1552- 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)1556-1557- with pytest.raises(ValueError) as e:1558- requests.get(httpbin('get'), timeout="foo")1559- assert 'must be an int or float' in str(e)1560-1561- def test_none_timeout(self, httpbin):1562- """ Check that you can set None as a valid timeout value.1563-1564- 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 == 2001572-1573- 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- pass1579-1580- 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)1587-1588- 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- pass1594-1595- 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.ok1599-1600-1601-SendCall = collections.namedtuple('SendCall', ('args', 'kwargs'))1602-1603-1604-class 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 = False1611-1612- def send(self, *args, **kwargs):1613- self.calls.append(SendCall(args, kwargs))1614- return self.build_response()1615-1616- def build_response(self):1617- request = self.calls[-1].args[0]1618- r = requests.Response()1619-1620- try:1621- r.status_code = int(self.redirects.pop(0))1622- except IndexError:1623- r.status_code = 2001624-1625- r.headers = CaseInsensitiveDict({'Location': '/'})1626- r.raw = self._build_raw()1627- r.request = request1628- return r1629-1630- def _build_raw(self):1631- string = StringIO.StringIO('')1632- setattr(string, 'release_conn', lambda *args: args)1633- return string1634-1635-1636-class TestRedirects:1637- default_keyword_args = {1638- 'stream': False,1639- 'verify': True,1640- 'cert': None,1641- 'timeout': None,1642- 'allow_redirects': False,1643- 'proxies': {},1644- }1645-1646- 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_call1658-1659-1660-1661-@pytest.fixture1662-def list_of_tuples():1663- return [1664- (('a', 'b'), ('c', 'd')),1665- (('c', 'd'), ('a', 'b')),1666- (('a', 'b'), ('c', 'd'), ('e', 'f')),1667- ]1668-1669-1670-def 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)1684-1685-1686-def assert_copy(p, p_copy):1687- for attr in ('method', 'url', 'headers', '_cookies', 'body', 'hooks'):1688- assert getattr(p, attr) == getattr(p_copy, attr)1689-1690-1691-def test_prepared_request_empty_copy():1692- p = PreparedRequest()1693- assert_copy(p, p.copy())1694-1695-1696-def 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())1705-1706-1707-def 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())1717-1718-1719-def 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())1726-1727-1728-def 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- )))1734-1735- with pytest.raises(RetryError):1736- s.get(httpbin('status/500'))1737-1738-1739-def test_urllib3_pool_connection_closed(httpbin):1740- s = requests.Session()1741- s.mount('http://', HTTPAdapter(pool_connections=0, pool_maxsize=0))1742-1743- try:1744- s.get(httpbin('status/200'))1745- except ConnectionError as e:1746- assert u"Pool is closed." in str(e)1747-1748-1749-def test_vendor_aliases():1750- from requests.packages import urllib31751- from requests.packages import chardet1752-1753- with pytest.raises(ImportError):1754- from requests.packages import webbrowser1755-1756-class 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()1772-1773- def test_server_closes(self):1774- with Server.basic_response_server() as (host, port):1775- sock = socket.socket()1776- sock.connect((host, port))1777-1778- sock.close()1779-1780- with pytest.raises(socket.error):1781- new_sock = socket.socket()1782- new_sock.connect((host, port))1783-1784- 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- )1790-1791- with server as (host, port):1792- r = requests.get('http://{}:{}'.format(host, port))1793-1794- 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'1804-1805- def test_basic_waiting_server(self):1806- block_server = threading.Event()1807-1808- 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 block1815-1816- def test_multiple_requests(self):1817- requests_to_handle = 51818- 1819- server = Server.basic_response_server(requests_to_handle=requests_to_handle)1820-1821- 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 == 2001826-1827- # the (n+1)th request fails1828- with pytest.raises(requests.exceptions.ConnectionError):1829- r = requests.get(server_url)1830-1831- 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"1835-1836- 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()1843-1844- sock2.connect(address)1845- sock2.send(second_request.encode())1846- sock2.close()1847-1848- assert server.handler_results[0] == first_request1849- assert server.handler_results[1] == second_request1850-1851- def test_requests_after_timeout_are_not_received(self):1852- server = Server.basic_response_server(request_timeout=1)1853-1854- 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()1860-1861- assert server.handler_results[0] == ""1862-1863-1864- def test_request_recovery_with_bigger_timeout(self):1865- server = Server.basic_response_server(request_timeout=3)1866- data = "bananadine"1867-1868- 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] == data1876-1877-if __name__ == '__main__':1878- unittest.main()