Merge branch 'develop'
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by Kenneth Reitz · committed by Kenneth Reitz · parents 70fbd27, 0bfc029 · Browse files · 8 files·+131 added−36 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
8 files+131 added−36 removed
- other:+131 added−36 removed
Provenance
- Commit
9ed9304- Tree
dd43d6f- Author
Kenneth Reitz <me@kennethreitz.com>- Committer
Kenneth Reitz <me@kennethreitz.com>- Parent 1
70fbd27- Parent 2
0bfc029
8 files changed+131 added−36 removed
modified:docs/user/advanced.rst+21 added
241 unmodified lines242 >>> requests.get('http://pizzabin.org/admin', auth=PizzaAuth('kenneth'))243 <Response [200]>244 245 246+Streaming Requests247+------------------248+249+With ``requests.Response.iter_lines()`` you can easily iterate over streaming 250+APIs such as the `Twitter Streaming API <https://dev.twitter.com/docs/streaming-api>`_.251+252+To use the Twitter Streaming API to track the keyword "requests":253+254+::255+256+ import requests257+ import json258+259+ r = requests.post('https://stream.twitter.com/1/statuses/filter.json',260+ data={'track': 'requests'}, auth=('username', 'password'))261+262+ for line in r.iter_lines():263+ if line: # filter out keep-alive new lines264+ print json.loads(line)265+266+267 Verbose Logging268 ---------------269 270 If you want to get a good look at what HTTP requests are being sent8 unmodified linesmodified:docs/index.rst+1 added-1 removed
36 unmodified lines37 `The Washington Post <http://www.washingtonpost.com/>`_,38 `Twitter, Inc <http://twitter.com>`_,39 `Readability <http://readability.com>`_, and40 Federal US Institutions41-use Requests internally. It has been installed over 45,000 times from PyPI.41+use Requests internally. It has been installed over 60,000 times from PyPI.42 43 **Armin Ronacher**44 Requests is the perfect example how beautiful an API can be with the45 right level of abstraction.86 unmodified linesmodified:requests/__init__.py+2 added-2 removed
13 unmodified lines14 15 """16 17 __title__ = 'requests'18-__version__ = '0.8.6'19-__build__ = 0x00080618+__version__ = '0.8.7'19+__build__ = 0x00080720 __author__ = 'Kenneth Reitz'21 __license__ = 'ISC'22 __copyright__ = 'Copyright 2011 Kenneth Reitz'23 11 unmodified linesmodified:requests/async.py+5 added
34 unmodified lines35 36 kwargs['return_response'] = False37 kwargs['prefetch'] = True38 39+ config = kwargs.get('config', {})40+ config.update(safe_mode=True)41+42+ kwargs['config'] = config43+44 return f(*args, **kwargs)45 46 return wrapped47 49 unmodified linesmodified:requests/models.py+50 added-31 removed
16 unmodified lines17 from .structures import CaseInsensitiveDict18 from .status_codes import codes19 from .packages import oreos20 from .auth import HTTPBasicAuth, HTTPProxyAuth21+from .packages.urllib3.response import HTTPResponse22 from .packages.urllib3.exceptions import MaxRetryError23 from .packages.urllib3.exceptions import SSLError as _SSLError24 from .packages.urllib3.exceptions import HTTPError as _HTTPError25 from .packages.urllib3 import connectionpool, poolmanager26 from .packages.urllib3.filepost import encode_multipart_formdata27 from .exceptions import (27- Timeout, URLRequired, TooManyRedirects, HTTPError, ConnectionError)28+ ConnectionError, HTTPError, RequestException, Timeout, TooManyRedirects,29+ URLRequired)30 from .utils import (31 get_encoding_from_headers, stream_decode_response_unicode,32 decode_gzip, stream_decode_gzip, guess_filename, requote_path)33 138 unmodified lines172 173 # Save cookies in Response.174 response.cookies = cookies175 176+ # No exceptions were harmed in the making of this request.177+ response.error = getattr(resp, 'error', None)178+179 # Save original response for later.180 response.raw = resp181 182 if is_error:260 unmodified lines443 # Attach Cookie header to request.444 self.headers['Cookie'] = cookie_header445 446 try:447+ # The inner try .. except re-raises certain exceptions as448+ # internal exception types; the outer suppresses exceptions449+ # when safe mode is set.450+ try:442- # Send the request.443- r = conn.urlopen(444- method=self.method,445- url=self.path_url,446- body=body,447- headers=self.headers,448- redirect=False,449- assert_same_host=False,450- preload_content=False,451- decode_content=False,452- retries=self.config.get('max_retries', 0),453- timeout=self.timeout,454- )455- self.sent = True451+ # Send the request.452+ r = conn.urlopen(453+ method=self.method,454+ url=self.path_url,455+ body=body,456+ headers=self.headers,457+ redirect=False,458+ assert_same_host=False,459+ preload_content=False,460+ decode_content=False,461+ retries=self.config.get('max_retries', 0),462+ timeout=self.timeout,463+ )464+ self.sent = True465 457-458- except MaxRetryError, e:466+ except MaxRetryError, e:459- if not self.config.get('safe_mode', False):467 raise ConnectionError(e)461- else:462- r = None468 464- except (_SSLError, _HTTPError), e:465- if not self.config.get('safe_mode', False):469+ except (_SSLError, _HTTPError), e:470 raise Timeout('Request timed out.')471 472+ except RequestException, e:473+ if self.config.get('safe_mode', False):474+ # In safe mode, catch the exception and attach it to 475+ # a blank urllib3.HTTPResponse object.476+ r = HTTPResponse()477+ r.error = e478+ else:479+ raise480+481 self._build_response(r)482 483 # Response manipulation hook.484 self.response = dispatch_hook('response', self.hooks, self.response)122 unmodified lines607 'The content for this response was already consumed'608 )609 610 def generate():611+ if self.raw is not None:598- chunk = []612+ chunk = []613 600- while 1:601- c = self.raw.read(1)602- if not c:603- break614+ while 1:615+ c = self.raw.read(1)616+ if not c:617+ break618 605- if c in newlines:619+ if c in newlines:620+ yield ''.join(chunk)621+ chunk = []622+ else:623+ chunk.append(c)624+625+ # Yield the remainder, in case the response626+ # did not terminate with a newline627+ if chunk:628 yield ''.join(chunk)607- chunk = []608- else:609- chunk.append(c)629 630 self._content_consumed = True631 632 gen = generate()76 unmodified linesmodified:AUTHORS.rst+3 added-1 removed
63 unmodified lines64 - Robert Gieseke65 - Idan Gazit66 - Ed Summers67 - Chris Van Horne68-- Christopher Davis68+- Christopher Davis69+- Ori Livneh70+- Jason Emerickmodified:HISTORY.rst+8 added-1 removed
1 History2 -------3 4+0.8.7 (2011-12-24)5+++++++++++++++++++6+7+* iter_lines last-line truncation fix8+* Force safe_mode for async requests9+* Handle safe_mode exceptions more consistently10+* Fix iteration on null responses in safe_mode11+12 0.8.6 (2011-12-18)13 ++++++++++++++++++14 15 * Socket timeout fixes.16 * Proxy Authorization support.17 10-18 0.8.5 (2011-12-14)19 ++++++++++++++++++20 21 * Response.iter_lines!280 unmodified linesmodified:test_requests.py+41 added
1 unmodified line2 # -*- coding: utf-8 -*-3 4 from __future__ import with_statement5 6+import StringIO7 import time8 import os9 import unittest10 592 unmodified lines603 len_lines = len([l for l in r.iter_lines()])604 605 self.assertEqual(i, len_lines)606 607+ # Test 'dangling' fragment in responses that do not terminate in608+ # a newline.609+ quote = (610+ '''Why will he not upon our fair request\n'''611+ '''Untent his person and share the air with us?'''612+ )613+614+ # Make a request and monkey-patch its contents615+ r = requests.get(httpbin('get'))616+ r.raw = StringIO.StringIO(quote)617+618+ # Make sure iter_lines doesn't chop the trailing bit619+ lines = '\n'.join(r.iter_lines())620+ self.assertEqual(lines, quote)621+622+ def test_safe_mode(self):623+624+ safe = requests.session(config=dict(safe_mode=True))625+626+ # Safe mode creates empty responses for failed requests.627+ # Iterating on these responses should produce empty sequences628+ r = safe.get('http://_/')629+ self.assertEquals(list(r.iter_lines()), [])630+ self.assertIsInstance(r.error, requests.exceptions.ConnectionError)631+632+ r = safe.get('http://_/')633+ self.assertEquals(list(r.iter_content()), [])634+ self.assertIsInstance(r.error, requests.exceptions.ConnectionError)635+636+ # When not in safe mode, should raise Timeout exception637+ with self.assertRaises(requests.exceptions.Timeout):638+ r = requests.get(httpbin('stream', '1000'), timeout=0.0001)639+640+ # In safe mode, should return a blank response641+ r = requests.get(httpbin('stream', '1000'), timeout=0.0001,642+ config=dict(safe_mode=True))643+ self.assertIsNone(r.content)644+ self.assertIsInstance(r.error, requests.exceptions.Timeout)645+646+647 if __name__ == '__main__':648 unittest.main()