Skip to content
Myr

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

8 files+131 added−36 removed

modified:docs/user/advanced.rst+21 added
241 unmodified lines
242 >>> requests.get('http://pizzabin.org/admin', auth=PizzaAuth('kenneth'))243 <Response [200]>244245246Streaming Requests247------------------248249With ``requests.Response.iter_lines()`` you can easily iterate over streaming 250APIs such as the `Twitter Streaming API <https://dev.twitter.com/docs/streaming-api>`_.251252To use the Twitter Streaming API to track the keyword "requests":253254::255256 import requests257 import json258259 r = requests.post('https://stream.twitter.com/1/statuses/filter.json',260 data={'track': 'requests'}, auth=('username', 'password'))261262 for line in r.iter_lines():263 if line: # filter out keep-alive new lines264 print json.loads(line)265266267Verbose Logging268---------------269270If you want to get a good look at what HTTP requests are being sent
8 unmodified lines
modified:docs/index.rst+1 added-1 removed
36 unmodified lines
37`The Washington Post <http://www.washingtonpost.com/>`_,38`Twitter, Inc <http://twitter.com>`_,39`Readability <http://readability.com>`_, and40Federal US Institutions41use Requests internally. It has been installed over 45,000 times from PyPI.41use Requests internally. It has been installed over 60,000 times from PyPI.4243**Armin Ronacher**44 Requests is the perfect example how beautiful an API can be with the45 right level of abstraction.
86 unmodified lines
modified:requests/__init__.py+2 added-2 removed
13 unmodified lines
1415"""1617__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 lines
modified:requests/async.py+5 added
34 unmodified lines
3536 kwargs['return_response'] = False37 kwargs['prefetch'] = True3839 config = kwargs.get('config', {})40 config.update(safe_mode=True)4142 kwargs['config'] = config4344 return f(*args, **kwargs)4546 return wrapped47
49 unmodified lines
modified:requests/models.py+50 added-31 removed
16 unmodified lines
17from .structures import CaseInsensitiveDict18from .status_codes import codes19from .packages import oreos20from .auth import HTTPBasicAuth, HTTPProxyAuth21from .packages.urllib3.response import HTTPResponse22from .packages.urllib3.exceptions import MaxRetryError23from .packages.urllib3.exceptions import SSLError as _SSLError24from .packages.urllib3.exceptions import HTTPError as _HTTPError25from .packages.urllib3 import connectionpool, poolmanager26from .packages.urllib3.filepost import encode_multipart_formdata27from .exceptions import (27 Timeout, URLRequired, TooManyRedirects, HTTPError, ConnectionError)28 ConnectionError, HTTPError, RequestException, Timeout, TooManyRedirects,29 URLRequired)30from .utils import (31 get_encoding_from_headers, stream_decode_response_unicode,32 decode_gzip, stream_decode_gzip, guess_filename, requote_path)33
138 unmodified lines
172173 # Save cookies in Response.174 response.cookies = cookies175176 # No exceptions were harmed in the making of this request.177 response.error = getattr(resp, 'error', None)178179 # Save original response for later.180 response.raw = resp181182 if is_error:
260 unmodified lines
443 # Attach Cookie header to request.444 self.headers['Cookie'] = cookie_header445446 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 = True465457458 except MaxRetryError, e:466 except MaxRetryError, e:459 if not self.config.get('safe_mode', False):467 raise ConnectionError(e)461 else:462 r = None468464 except (_SSLError, _HTTPError), e:465 if not self.config.get('safe_mode', False):469 except (_SSLError, _HTTPError), e:470 raise Timeout('Request timed out.')471472 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 raise480481 self._build_response(r)482483 # Response manipulation hook.484 self.response = dispatch_hook('response', self.hooks, self.response)
122 unmodified lines
607 'The content for this response was already consumed'608 )609610 def generate():611 if self.raw is not None:598 chunk = []612 chunk = []613600 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 break618605 if c in newlines:619 if c in newlines:620 yield ''.join(chunk)621 chunk = []622 else:623 chunk.append(c)624625 # 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)629630 self._content_consumed = True631632 gen = generate()
76 unmodified lines
modified:AUTHORS.rst+3 added-1 removed
63 unmodified lines
64- Robert Gieseke65- Idan Gazit66- Ed Summers67- Chris Van Horne68- Christopher Davis68- Christopher Davis69- Ori Livneh70- Jason Emerick
modified:HISTORY.rst+8 added-1 removed
1History2-------340.8.7 (2011-12-24)5++++++++++++++++++67* 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_mode11120.8.6 (2011-12-18)13++++++++++++++++++1415* Socket timeout fixes.16* Proxy Authorization support.1710180.8.5 (2011-12-14)19++++++++++++++++++2021* Response.iter_lines!
280 unmodified lines
modified:test_requests.py+41 added
1 unmodified line
2# -*- coding: utf-8 -*-34from __future__ import with_statement56import StringIO7import time8import os9import unittest10
592 unmodified lines
603 len_lines = len([l for l in r.iter_lines()])604605 self.assertEqual(i, len_lines)606607 # 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 )613614 # Make a request and monkey-patch its contents615 r = requests.get(httpbin('get'))616 r.raw = StringIO.StringIO(quote)617618 # Make sure iter_lines doesn't chop the trailing bit619 lines = '\n'.join(r.iter_lines())620 self.assertEqual(lines, quote)621622 def test_safe_mode(self):623624 safe = requests.session(config=dict(safe_mode=True))625626 # 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)631632 r = safe.get('http://_/')633 self.assertEquals(list(r.iter_content()), [])634 self.assertIsInstance(r.error, requests.exceptions.ConnectionError)635636 # 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)639640 # 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)645646647if __name__ == '__main__':648 unittest.main()