Merge remote-tracking branch 'origin/master'
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 f35363e, c8d3dcb · Browse files · 13 files·+170 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
13 files+170 added−36 removed
- other:+170 added−36 removed
Provenance
- Commit
011f6da- Tree
0511a1b- Author
Kenneth Reitz <me@kennethreitz.com>- Committer
Kenneth Reitz <me@kennethreitz.com>- Parent 1
f35363e- Parent 2
c8d3dcb
13 files changed+170 added−36 removed
modified:docs/user/advanced.rst+6 added-4 removed
20 unmodified lines21 22 s.get('http://httpbin.org/cookies/set/sessioncookie/123456789')23 r = s.get("http://httpbin.org/cookies")24 25- print r.text25+ print(r.text)26 # '{"cookies": {"sessioncookie": "123456789"}}'27 28 29 Sessions can also be used to provide default data to the request methods. This244 unmodified lines274 ------------------275 276 With ``requests.Response.iter_lines()`` you can easily iterate over streaming277 APIs such as the `Twitter Streaming API <https://dev.twitter.com/docs/streaming-api>`_.278+Simply set ``stream`` to ``True`` and iterate over the response with ``iter_lines()``::279 279-To use the Twitter Streaming API to track the keyword "requests"::280-280 import json281 import requests282 283 r = requests.get('http://httpbin.org/stream/20', stream=True)19 unmodified lines303 }304 305 requests.get("http://example.org", proxies=proxies)306 308-You can also configure proxies by environment variables ``HTTP_PROXY`` and ``HTTPS_PROXY``.307+You can also configure proxies by setting the environment variables308+``HTTP_PROXY`` and ``HTTPS_PROXY``.309 310 ::311 312 $ export HTTP_PROXY="http://10.10.1.10:3128"7 unmodified lines320 proxies = {321 "http": "http://user:pass@10.10.1.10:3128/",322 }323 324+Note that proxy URLs must include the scheme.325+326 Compliance327 ----------328 329 Requests is intended to be compliant with all relevant specifications and267 unmodified linesmodified:docs/user/quickstart.rst+6 added-7 removed
66 unmodified lines67 >>> r = requests.get("http://httpbin.org/get", params=payload)68 69 You can see that the URL has been correctly encoded by printing the URL::70 71- >>> print r.url71+ >>> print(r.url)72 http://httpbin.org/get?key2=value2&key1=value173 74 Note that any dictionary key whose value is ``None`` will not be added to the75 URL's query string.262 unmodified lines338 339 Redirection and History340 -----------------------341 342-Requests will automatically perform location redirection while using the GET343-and OPTIONS verbs.342+Requests will automatically perform location redirection for all verbs except343+HEAD.344 345 GitHub redirects all HTTP requests to HTTPS. We can use the ``history`` method346 of the Response object to track redirection. Let's see what GitHub does::347 8 unmodified lines356 The :class:`Response.history` list contains the :class:`Request` objects that357 were created in order to complete the request. The list is sorted from the358 oldest to the most recent request.359 360-If you're using GET or OPTIONS, you can disable redirection handling with the361-``allow_redirects`` parameter::360+If you're using GET, OPTIONS, POST, PUT, PATCH or DELETE, you can disable361+redirection handling with the ``allow_redirects`` parameter::362 363 >>> r = requests.get('http://github.com', allow_redirects=False)364 >>> r.status_code365 301366 >>> r.history367 []368 369-If you're using POST, PUT, PATCH, DELETE or HEAD, you can enable370-redirection as well::369+If you're using HEAD, you can enable redirection as well::370 371 >>> r = requests.post('http://github.com', allow_redirects=True)372 >>> r.url373 'https://github.com/'45 unmodified linesmodified:docs/api.rst+70 added
191 unmodified lines192 193 .. _ISC: http://opensource.org/licenses/ISC194 .. _Apache 2.0: http://opensource.org/licenses/Apache-2.0195 196+197+Migrating to 2.x198+----------------199+200+201+Compared with the 1.0 release, there were relatively few backwards202+incompatible changes, but there are still a few issues to be aware of with203+this major release.204+205+For more details on the changes in this release including new APIs, links206+to the relevant GitHub issues and some of the bug fixes, read Cory's blog_207+on the subject.208+209+.. _blog: http://lukasa.co.uk/2013/09/Requests_20/210+211+212+API Changes213+~~~~~~~~~~~214+215+* There were a couple changes to how Requests handles exceptions.216+ ``RequestException`` is now a subclass of ``IOError`` rather than217+ ``RuntimeError`` as that more accurately categorizes the type of error.218+ In addition, an invalid URL escape sequence now raises a subclass of219+ ``RequestException`` rather than a ``ValueError``.220+221+ ::222+223+ requests.get('http://%zz/') # raises requests.exceptions.InvalidURL224+225+ Lastly, ``httplib.IncompleteRead`` exceptions caused by incorrect chunked226+ encoding will now raise a Requests ``ChunkedEncodingError`` instead.227+228+* The proxy API has changed slightly. The scheme for a proxy URL is now229+ required.230+231+ ::232+233+ proxies = {234+ "http": "10.10.1.10:3128", # use http://10.10.1.10:3128 instead235+ }236+237+ # In requests 1.x, this was legal, in requests 2.x,238+ # this raises requests.exceptions.MissingSchema239+ requests.get("http://example.org", proxies=proxies)240+241+242+Behavioral Changes243+~~~~~~~~~~~~~~~~~~244+245+* Keys in the ``headers`` dictionary are now native strings on all Python246+ versions, i.e. bytestrings on Python 2 and unicode on Python 3. If the247+ keys are not native strings (unicode on Python2 or bytestrings on Python 3)248+ they will be converted to the native string type assuming UTF-8 encoding.249+250+* Timeouts behave slightly differently. On streaming requests, the timeout251+ only applies to the connection attempt. On regular requests, the timeout252+ is applied to the connection process and downloading the full body.253+254+ ::255+256+ tarball_url = 'https://github.com/kennethreitz/requests/tarball/master'257+258+ # One second timeout for the connection attempt259+ # Unlimited time to download the tarball260+ r = requests.get(tarball_url, stream=True, timeout=1)261+262+ # One second timeout for the connection attempt263+ # Another full second timeout to download the tarball264+ r = requests.get(tarball_url, timeout=1)265+modified:requests/__init__.py+1 added-1 removed
21 unmodified lines22 ... or POST:23 24 >>> payload = dict(key1='value1', key2='value2')25 >>> r = requests.post("http://httpbin.org/post", data=payload)26- >>> print r.text26+ >>> print(r.text)27 {28 ...29 "form": {30 "key2": "value2",47 unmodified linesmodified:requests/adapters.py+10 added-5 removed
20 unmodified lines21 from .packages.urllib3.exceptions import MaxRetryError22 from .packages.urllib3.exceptions import TimeoutError23 from .packages.urllib3.exceptions import SSLError as _SSLError24 from .packages.urllib3.exceptions import HTTPError as _HTTPError25+from .packages.urllib3.exceptions import ProxyError as _ProxyError26 from .cookies import extract_cookies_to_jar26-from .exceptions import ConnectionError, Timeout, SSLError27+from .exceptions import ConnectionError, Timeout, SSLError, ProxyError28 from .auth import _basic_auth_str29 30 DEFAULT_POOLBLOCK = False31 DEFAULT_POOLSIZE = 10188 unmodified lines220 221 def request_url(self, request, proxies):222 """Obtain the url to use when making the final request.223 223- If the message is being sent through a proxy, the full URL has to be224- used. Otherwise, we should only use the path portion of the URL.224+ If the message is being sent through a HTTP proxy, the full URL has to225+ be used. Otherwise, we should only use the path portion of the URL.226 227 This should not be called from user code, and is only exposed for use228 when subclassing the229 :class:`HTTPAdapter <requests.adapters.HTTPAdapter>`.1 unmodified line231 :param request: The :class:`PreparedRequest <PreparedRequest>` being sent.232 :param proxies: A dictionary of schemes to proxy URLs.233 """234 proxies = proxies or {}235+ scheme = urlparse(request.url).scheme.lower()234- proxy = proxies.get(urlparse(request.url).scheme)236+ proxy = proxies.get(scheme)237 236- if proxy:238+ if proxy and scheme != 'https':239 url, _ = urldefrag(request.url)240 else:241 url = request.path_url242 111 unmodified lines354 355 except MaxRetryError as e:356 raise ConnectionError(e)357 358+ except _ProxyError as e:359+ raise ProxyError(e)360+361 except (_SSLError, _HTTPError) as e:362 if isinstance(e, _SSLError):363 raise SSLError(e)364 elif isinstance(e, TimeoutError):10 unmodified linesmodified:requests/cookies.py+8 added-2 removed
390 unmodified lines391 rfc2109=False,)392 return c393 394 395-def cookiejar_from_dict(cookie_dict, cookiejar=None):395+def cookiejar_from_dict(cookie_dict, cookiejar=None, overwrite=True):396 """Returns a CookieJar from a key/value dictionary.397 398 :param cookie_dict: Dict of key/values to insert into CookieJar.399+ :param cookiejar: (optional) A cookiejar to add the cookies to.400+ :param overwrite: (optional) If False, will not replace cookies401+ already in the jar with new ones.402 """403 if cookiejar is None:404 cookiejar = RequestsCookieJar()405 406 if cookie_dict is not None:407+ names_from_jar = [cookie.name for cookie in cookiejar]408 for name in cookie_dict:409+ if overwrite or (name not in names_from_jar):405- cookiejar.set_cookie(create_cookie(name, cookie_dict[name]))410+ cookiejar.set_cookie(create_cookie(name, cookie_dict[name]))411+412 return cookiejarmodified:requests/exceptions.py+4 added
25 unmodified lines26 class ConnectionError(RequestException):27 """A Connection error occurred."""28 29 30+class ProxyError(ConnectionError):31+ """A proxy error occurred."""32+33+34 class SSLError(ConnectionError):35 """An SSL error occurred."""36 37 26 unmodified linesmodified:requests/models.py+13 added-10 removed
15 unmodified lines16 from .structures import CaseInsensitiveDict17 18 from .auth import HTTPBasicAuth19 from .cookies import cookiejar_from_dict, get_cookie_header20+from .packages.urllib3.fields import RequestField21 from .packages.urllib3.filepost import encode_multipart_formdata22 from .packages.urllib3.util import parse_url23 from .exceptions import (24 HTTPError, RequestException, MissingSchema, InvalidURL,65 unmodified lines90 def _encode_files(files, data):91 """Build the body for a multipart/form-data request.92 93 Will successfully encode files when passed as a dict or a list of93- 2-tuples. Order is retained if data is a list of 2-tuples but abritrary94+ 2-tuples. Order is retained if data is a list of 2-tuples but arbitrary95 if parameters are supplied as a dict.96 97 """98 if (not files):20 unmodified lines119 120 for (k, v) in files:121 # support for explicit filename122 ft = None123+ fh = None124 if isinstance(v, (tuple, list)):125 if len(v) == 2:126 fn, fp = v125- else:127+ elif len(v) == 3:128 fn, fp, ft = v129+ else:130+ fn, fp, ft, fh = v131 else:132 fn = guess_filename(v) or k133 fp = v134 if isinstance(fp, str):135 fp = StringIO(fp)136 if isinstance(fp, bytes):137 fp = BytesIO(fp)138 135- if ft:136- new_v = (fn, fp.read(), ft)137- else:138- new_v = (fn, fp.read())139- new_fields.append((k, new_v))139+ rf = RequestField(name=k, data=fp.read(),140+ filename=fn, headers=fh)141+ rf.make_multipart(content_type=ft)142+ new_fields.append(rf)143 144 body, content_type = encode_multipart_formdata(new_fields)145 146 return body, content_type150 unmodified lines297 def copy(self):298 p = PreparedRequest()299 p.method = self.method300 p.url = self.url298- p.headers = self.headers301+ p.headers = self.headers.copy()302 p.body = self.body303 p.hooks = self.hooks304 return p305 271 unmodified lines577 except IncompleteRead as e:578 raise ChunkedEncodingError(e)579 except AttributeError:580 # Standard file-like object.578- while 1:581+ while True:582 chunk = self.raw.read(chunk_size)583 if not chunk:584 break585 yield chunk103 unmodified lines689 # a best guess).690 encoding = guess_json_utf(self.content)691 if encoding is not None:692 return json.loads(self.content.decode(encoding), **kwargs)690- return json.loads(self.text or self.content, **kwargs)693+ return json.loads(self.text, **kwargs)694 695 @property696 def links(self):697 """Returns the parsed header links of the response, if any."""36 unmodified linesmodified:requests/sessions.py+8 added-4 removed
10 unmodified lines11 import os12 from collections import Mapping13 from datetime import datetime14 15-from .compat import cookielib, OrderedDict, urljoin, urlparse15+from .compat import cookielib, OrderedDict, urljoin, urlparse, urlunparse16 from .cookies import cookiejar_from_dict, extract_cookies_to_jar, RequestsCookieJar17 from .models import Request, PreparedRequest18 from .hooks import default_hooks, dispatch_hook19 from .utils import to_key_val_list, default_headers72 unmodified lines92 parsed_rurl = urlparse(resp.url)93 url = '%s:%s' % (parsed_rurl.scheme, url)94 95 # The scheme should be lower case...96- if '://' in url:97- scheme, uri = url.split('://', 1)98- url = '%s://%s' % (scheme.lower(), uri)96+ parsed = urlparse(url)97+ parsed = (parsed.scheme.lower(), parsed.netloc, parsed.path,98+ parsed.params, parsed.query, parsed.fragment)99+ url = urlunparse(parsed)100 101 # Facilitate non-RFC2616-compliant 'location' headers102 # (e.g. '/path/to/resource' instead of 'http://domain.tld/path/to/resource')103 # Compliant with RFC3986, we percent encode the url.218 unmodified lines322 hooks = hooks,323 )324 prep = self.prepare_request(req)325 326+ # Add param cookies to session cookies327+ self.cookies = cookiejar_from_dict(cookies, cookiejar=self.cookies, overwrite=False)328+329 proxies = proxies or {}330 331 # Gather clues from the surrounding environment.332 if self.trust_env:199 unmodified linesmodified:requests/utils.py+12 added-1 removed
10 unmodified lines11 12 import cgi13 import codecs14 import collections15+import io16 import os17 import platform18 import re19 import sys26 unmodified lines46 47 def super_len(o):48 if hasattr(o, '__len__'):49 return len(o)50+51 if hasattr(o, 'len'):52 return o.len53+54 if hasattr(o, 'fileno'):55+ try:56+ fileno = o.fileno()57+ except io.UnsupportedOperation:58+ pass59+ else:52- return os.fstat(o.fileno()).st_size60+ return os.fstat(fileno).st_size61 62+ if hasattr(o, 'getvalue'):63+ # e.g. BytesIO, cStringIO.StringI64+ return len(o.getvalue())65 66 def get_netrc_auth(url):67 """Returns the Requests tuple auth for a given url from netrc."""68 514 unmodified linesmodified:AUTHORS.rst+4 added-1 removed
133 unmodified lines134 - Flavio Curella135 - David Pursehouse <david.pursehouse@gmail.com> @dpursehouse136 - Jon Parise137 - Alexander Karpinsky @homm86138-- Marc Schlaich @schlamar138+- Marc Schlaich @schlamar139+- Park Ilsu <daftonshady@gmail.com> @daftshady140+- Matt Spitz @mattspitz141+- Vikram Oberoi @voberoimodified:HISTORY.rst+1 added-1 removed
40 unmodified lines41 - Support for mixed case schemes.42 - Better handling of streaming downloads.43 - Retrieve environment proxies from more locations.44 - Minor cookies fixes.45-- Imroved redirect behaviour.45+- Improved redirect behaviour.46 - Improved streaming behaviour, particularly for compressed data.47 - Miscellaneous small Python 3 text encoding bugs.48 - ``.netrc`` no longer overrides explicit auth.49 - Cookies set by hooks are now correctly persisted on Sessions.659 unmodified linesmodified:test_requests.py+27 added
162 unmodified lines163 s = requests.session()164 s.get(httpbin('cookies/set?foo="bar:baz"'))165 self.assertTrue(s.cookies['foo'] == '"bar:baz"')166 167+ def test_cookie_persists_via_api(self):168+ s = requests.session()169+ r = s.get(httpbin('redirect/1'), cookies={'foo':'bar'})170+ self.assertTrue('foo' in r.request.headers['Cookie'])171+ self.assertTrue('foo' in r.history[0].request.headers['Cookie'])172+173 def test_request_cookie_overrides_session_cookie(self):174 s = requests.session()175 s.cookies['foo'] = 'bar'176 r = s.get(httpbin('cookies'), cookies={'foo': 'baz'})695 unmodified lines872 self.assertEqual(frozenset(cid.keys()), keyset)873 self.assertEqual(frozenset(cid), keyset)874 875 876+class UtilsTestCase(unittest.TestCase):877+878+ def test_super_len_io_streams(self):879+ """ Ensures that we properly deal with different kinds of IO streams. """880+ # uses StringIO or io.StringIO (see import above)881+ from io import BytesIO882+ from requests.utils import super_len883+884+ self.assertEqual(super_len(StringIO.StringIO()), 0)885+ self.assertEqual(super_len(StringIO.StringIO('with so much drama in the LBC')), 29)886+887+ self.assertEqual(super_len(BytesIO()), 0)888+ self.assertEqual(super_len(BytesIO(b"it's kinda hard bein' snoop d-o-double-g")), 40)889+890+ try:891+ import cStringIO892+ except ImportError:893+ pass894+ else:895+ self.assertEqual(super_len(cStringIO.StringIO('but some how, some way...')), 25)896+897 if __name__ == '__main__':898 unittest.main()