Skip to content
Myr

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

13 files+170 added−36 removed

modified:docs/user/advanced.rst+6 added-4 removed
20 unmodified lines
2122 s.get('http://httpbin.org/cookies/set/sessioncookie/123456789')23 r = s.get("http://httpbin.org/cookies")2425 print r.text25 print(r.text)26 # '{"cookies": {"sessioncookie": "123456789"}}'272829Sessions can also be used to provide default data to the request methods. This
244 unmodified lines
274------------------275276With ``requests.Response.iter_lines()`` you can easily iterate over streaming277APIs such as the `Twitter Streaming API <https://dev.twitter.com/docs/streaming-api>`_.278Simply set ``stream`` to ``True`` and iterate over the response with ``iter_lines()``::279279To use the Twitter Streaming API to track the keyword "requests"::280280 import json281 import requests282283 r = requests.get('http://httpbin.org/stream/20', stream=True)
19 unmodified lines
303 }304305 requests.get("http://example.org", proxies=proxies)306308You can also configure proxies by environment variables ``HTTP_PROXY`` and ``HTTPS_PROXY``.307You can also configure proxies by setting the environment variables308``HTTP_PROXY`` and ``HTTPS_PROXY``.309310::311312 $ export HTTP_PROXY="http://10.10.1.10:3128"
7 unmodified lines
320 proxies = {321 "http": "http://user:pass@10.10.1.10:3128/",322 }323324Note that proxy URLs must include the scheme.325326Compliance327----------328329Requests is intended to be compliant with all relevant specifications and
267 unmodified lines
modified:docs/user/quickstart.rst+6 added-7 removed
66 unmodified lines
67 >>> r = requests.get("http://httpbin.org/get", params=payload)6869You can see that the URL has been correctly encoded by printing the URL::7071 >>> print r.url71 >>> print(r.url)72 http://httpbin.org/get?key2=value2&key1=value17374Note that any dictionary key whose value is ``None`` will not be added to the75URL's query string.
262 unmodified lines
338339Redirection and History340-----------------------341342Requests will automatically perform location redirection while using the GET343and OPTIONS verbs.342Requests will automatically perform location redirection for all verbs except343HEAD.344345GitHub redirects all HTTP requests to HTTPS. We can use the ``history`` method346of the Response object to track redirection. Let's see what GitHub does::347
8 unmodified lines
356The :class:`Response.history` list contains the :class:`Request` objects that357were created in order to complete the request. The list is sorted from the358oldest to the most recent request.359360If you're using GET or OPTIONS, you can disable redirection handling with the361``allow_redirects`` parameter::360If you're using GET, OPTIONS, POST, PUT, PATCH or DELETE, you can disable361redirection handling with the ``allow_redirects`` parameter::362363 >>> r = requests.get('http://github.com', allow_redirects=False)364 >>> r.status_code365 301366 >>> r.history367 []368369If you're using POST, PUT, PATCH, DELETE or HEAD, you can enable370redirection as well::369If you're using HEAD, you can enable redirection as well::370371 >>> r = requests.post('http://github.com', allow_redirects=True)372 >>> r.url373 'https://github.com/'
45 unmodified lines
modified:docs/api.rst+70 added
191 unmodified lines
192193.. _ISC: http://opensource.org/licenses/ISC194.. _Apache 2.0: http://opensource.org/licenses/Apache-2.0195196197Migrating to 2.x198----------------199200201Compared with the 1.0 release, there were relatively few backwards202incompatible changes, but there are still a few issues to be aware of with203this major release.204205For more details on the changes in this release including new APIs, links206to the relevant GitHub issues and some of the bug fixes, read Cory's blog_207on the subject.208209.. _blog: http://lukasa.co.uk/2013/09/Requests_20/210211212API Changes213~~~~~~~~~~~214215* 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``.220221 ::222223 requests.get('http://%zz/') # raises requests.exceptions.InvalidURL224225 Lastly, ``httplib.IncompleteRead`` exceptions caused by incorrect chunked226 encoding will now raise a Requests ``ChunkedEncodingError`` instead.227228* The proxy API has changed slightly. The scheme for a proxy URL is now229 required.230231 ::232233 proxies = {234 "http": "10.10.1.10:3128", # use http://10.10.1.10:3128 instead235 }236237 # In requests 1.x, this was legal, in requests 2.x,238 # this raises requests.exceptions.MissingSchema239 requests.get("http://example.org", proxies=proxies)240241242Behavioral Changes243~~~~~~~~~~~~~~~~~~244245* 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.249250* 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.253254 ::255256 tarball_url = 'https://github.com/kennethreitz/requests/tarball/master'257258 # One second timeout for the connection attempt259 # Unlimited time to download the tarball260 r = requests.get(tarball_url, stream=True, timeout=1)261262 # 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 lines
22... or POST:2324 >>> 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 lines
modified:requests/adapters.py+10 added-5 removed
20 unmodified lines
21from .packages.urllib3.exceptions import MaxRetryError22from .packages.urllib3.exceptions import TimeoutError23from .packages.urllib3.exceptions import SSLError as _SSLError24from .packages.urllib3.exceptions import HTTPError as _HTTPError25from .packages.urllib3.exceptions import ProxyError as _ProxyError26from .cookies import extract_cookies_to_jar26from .exceptions import ConnectionError, Timeout, SSLError27from .exceptions import ConnectionError, Timeout, SSLError, ProxyError28from .auth import _basic_auth_str2930DEFAULT_POOLBLOCK = False31DEFAULT_POOLSIZE = 10
188 unmodified lines
220221 def request_url(self, request, proxies):222 """Obtain the url to use when making the final request.223223 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.226227 This should not be called from user code, and is only exposed for use228 when subclassing the229 :class:`HTTPAdapter <requests.adapters.HTTPAdapter>`.
1 unmodified line
231 :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)237236 if proxy:238 if proxy and scheme != 'https':239 url, _ = urldefrag(request.url)240 else:241 url = request.path_url242
111 unmodified lines
354355 except MaxRetryError as e:356 raise ConnectionError(e)357358 except _ProxyError as e:359 raise ProxyError(e)360361 except (_SSLError, _HTTPError) as e:362 if isinstance(e, _SSLError):363 raise SSLError(e)364 elif isinstance(e, TimeoutError):
10 unmodified lines
modified:requests/cookies.py+8 added-2 removed
390 unmodified lines
391 rfc2109=False,)392 return c393394395def cookiejar_from_dict(cookie_dict, cookiejar=None):395def cookiejar_from_dict(cookie_dict, cookiejar=None, overwrite=True):396 """Returns a CookieJar from a key/value dictionary.397398 :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()405406 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]))411412 return cookiejar
modified:requests/exceptions.py+4 added
25 unmodified lines
26class ConnectionError(RequestException):27 """A Connection error occurred."""282930class ProxyError(ConnectionError):31 """A proxy error occurred."""323334class SSLError(ConnectionError):35 """An SSL error occurred."""3637
26 unmodified lines
modified:requests/models.py+13 added-10 removed
15 unmodified lines
16from .structures import CaseInsensitiveDict1718from .auth import HTTPBasicAuth19from .cookies import cookiejar_from_dict, get_cookie_header20from .packages.urllib3.fields import RequestField21from .packages.urllib3.filepost import encode_multipart_formdata22from .packages.urllib3.util import parse_url23from .exceptions import (24 HTTPError, RequestException, MissingSchema, InvalidURL,
65 unmodified lines
90 def _encode_files(files, data):91 """Build the body for a multipart/form-data request.9293 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.9697 """98 if (not files):
20 unmodified lines
119120 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)138135 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)143144 body, content_type = encode_multipart_formdata(new_fields)145146 return body, content_type
150 unmodified lines
297 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 lines
577 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 chunk
103 unmodified lines
689 # 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)694695 @property696 def links(self):697 """Returns the parsed header links of the response, if any."""
36 unmodified lines
modified:requests/sessions.py+8 added-4 removed
10 unmodified lines
11import os12from collections import Mapping13from datetime import datetime1415from .compat import cookielib, OrderedDict, urljoin, urlparse15from .compat import cookielib, OrderedDict, urljoin, urlparse, urlunparse16from .cookies import cookiejar_from_dict, extract_cookies_to_jar, RequestsCookieJar17from .models import Request, PreparedRequest18from .hooks import default_hooks, dispatch_hook19from .utils import to_key_val_list, default_headers
72 unmodified lines
92 parsed_rurl = urlparse(resp.url)93 url = '%s:%s' % (parsed_rurl.scheme, url)9495 # 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)100101 # 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 lines
322 hooks = hooks,323 )324 prep = self.prepare_request(req)325326 # Add param cookies to session cookies327 self.cookies = cookiejar_from_dict(cookies, cookiejar=self.cookies, overwrite=False)328329 proxies = proxies or {}330331 # Gather clues from the surrounding environment.332 if self.trust_env:
199 unmodified lines
modified:requests/utils.py+12 added-1 removed
10 unmodified lines
1112import cgi13import codecs14import collections15import io16import os17import platform18import re19import sys
26 unmodified lines
4647def super_len(o):48 if hasattr(o, '__len__'):49 return len(o)5051 if hasattr(o, 'len'):52 return o.len5354 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_size6162 if hasattr(o, 'getvalue'):63 # e.g. BytesIO, cStringIO.StringI64 return len(o.getvalue())6566def get_netrc_auth(url):67 """Returns the Requests tuple auth for a given url from netrc."""68
514 unmodified lines
modified:AUTHORS.rst+4 added-1 removed
133 unmodified lines
134- 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 @voberoi
modified:HISTORY.rst+1 added-1 removed
40 unmodified lines
41- 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 lines
modified:test_requests.py+27 added
162 unmodified lines
163 s = requests.session()164 s.get(httpbin('cookies/set?foo="bar:baz"'))165 self.assertTrue(s.cookies['foo'] == '"bar:baz"')166167 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'])172173 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 lines
872 self.assertEqual(frozenset(cid.keys()), keyset)873 self.assertEqual(frozenset(cid), keyset)874875876class UtilsTestCase(unittest.TestCase):877878 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_len883884 self.assertEqual(super_len(StringIO.StringIO()), 0)885 self.assertEqual(super_len(StringIO.StringIO('with so much drama in the LBC')), 29)886887 self.assertEqual(super_len(BytesIO()), 0)888 self.assertEqual(super_len(BytesIO(b"it's kinda hard bein' snoop d-o-double-g")), 40)889890 try:891 import cStringIO892 except ImportError:893 pass894 else:895 self.assertEqual(super_len(cStringIO.StringIO('but some how, some way...')), 25)896897if __name__ == '__main__':898 unittest.main()