Merge remote-tracking branch 'origin/develop' into 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 efdd645, a0df2cb · Browse files · 12 files·+119 added−75 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
12 files+119 added−75 removed
- tests:+32 added−4 removed
- other:+87 added−71 removed
Provenance
- Commit
ffc72ac- Tree
cc98fc0- Author
Kenneth Reitz <me@kennethreitz.com>- Committer
Kenneth Reitz <me@kennethreitz.com>- Parent 1
efdd645- Parent 2
a0df2cb
12 files changed+119 added−75 removed
modified:docs/user/advanced.rst+1 added-1 removed
281 unmodified lines282 import requests283 import json284 285 r = requests.post('https://stream.twitter.com/1/statuses/filter.json',286- data={'track': 'requests'}, auth=('username', 'password'))286+ data={'track': 'requests'}, auth=('username', 'password'), prefetch=False)287 288 for line in r.iter_lines():289 if line: # filter out keep-alive new lines290 print json.loads(line)271 unmodified linesmodified:docs/user/intro.rst+2 added-6 removed
15 unmodified lines16 #. Readability counts.17 18 All contributions to Requests should keep these important rules in mind.19 20+.. _`isc`:21 22 ISC License23 -----------24 16 unmodified lines41 42 Requests License43 ----------------44 44- Copyright (c) 2011, Kenneth Reitz45-46- Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies.47-48- THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.49-45+ .. include:: ../../LICENSEmodified:requests/compat.py+2 added
91 unmodified lines92 try:93 import cchardet as chardet94 except ImportError:95 from .packages import chardet96+ from .packages.urllib3.packages.ordered_dict import OrderedDict97 98 builtin_str = str99 bytes = str100 str = unicode8 unmodified lines109 from http import cookiejar as cookielib110 from http.cookies import Morsel111 from io import StringIO112 from .packages import chardet2 as chardet113+ from collections import OrderedDict114 115 builtin_str = str116 str = str117 bytes = bytes2 unmodified linesmodified:requests/defaults.py+1 added-1 removed
18 unmodified lines19 :pool_maxsize: The maximium size of an HTTP connection pool.20 :pool_connections: The number of active HTTP connection pools to use.21 :encode_uri: If true, URIs will automatically be percent-encoded.22 :trust_env: If true, the surrouding environment will be trusted (environ, netrc).23-:param store_cookies: If false, the received cookies as part of the HTTP response would be ignored.23+:store_cookies: If false, the received cookies as part of the HTTP response would be ignored.24 25 """26 27 SCHEMAS = ['http', 'https']23 unmodified linesmodified:requests/models.py+21 added-17 removed
32 unmodified lines33 stream_decode_response_unicode, get_netrc_auth, get_environ_proxies,34 to_key_val_list, DEFAULT_CA_BUNDLE_PATH, parse_header_links, iter_slices)35 from .compat import (36 cookielib, urlparse, urlunparse, urljoin, urlsplit, urlencode, str, bytes,37- StringIO, is_py2, chardet, json, builtin_str, numeric_types)37+ StringIO, is_py2, chardet, json, builtin_str)38 39 REDIRECT_STATI = (codes.moved, codes.found, codes.other, codes.temporary_moved)40 CONTENT_CHUNK_SIZE = 10 * 102441 68 unmodified lines110 111 # Dictionary mapping protocol to the URL of the proxy (e.g. {'http': 'foo.bar:3128'})112 self.proxies = dict(proxies or [])113 114+ for proxy_type,uri_ref in list(self.proxies.items()):115+ if not uri_ref:116+ del self.proxies[proxy_type]117+118 # If no proxies are given, allow configuration by environment variables119 # HTTP_PROXY and HTTPS_PROXY.120 if not self.proxies and self.config.get('trust_env'):121 self.proxies = get_environ_proxies()74 unmodified lines196 # Fallback to None if there's no status_code, for whatever reason.197 response.status_code = getattr(resp, 'status', None)198 199 # Make headers case-insensitive.196- response.headers = CaseInsensitiveDict(getattr(resp, 'headers', None))200+ response.headers = CaseInsensitiveDict(getattr(resp, 'headers', {}))201 202 # Set encoding.203 response.encoding = get_encoding_from_headers(response.headers)204 297 unmodified lines502 self.config.get('verbose').write('%s %s %s\n' % (503 datetime.now().isoformat(), self.method, url504 ))505 506+ # Use .netrc auth if none was provided.507+ if not self.auth and self.config.get('trust_env'):508+ self.auth = get_netrc_auth(url)509+510+ if self.auth:511+ if isinstance(self.auth, tuple) and len(self.auth) == 2:512+ # special-case basic HTTP auth513+ self.auth = HTTPBasicAuth(*self.auth)514+515+ # Allow auth to make its changes.516+ r = self.auth(self)517+518+ # Update self to reflect the auth changes.519+ self.__dict__.update(r.__dict__)520+521 # Nottin' on you.522 body = None523 content_type = None524 12 unmodified lines537 # Add content-type if it wasn't explicitly provided.538 if (content_type) and (not 'content-type' in self.headers):539 self.headers['Content-Type'] = content_type540 522- # Use .netrc auth if none was provided.523- if not self.auth and self.config.get('trust_env'):524- self.auth = get_netrc_auth(url)525-526- if self.auth:527- if isinstance(self.auth, tuple) and len(self.auth) == 2:528- # special-case basic HTTP auth529- self.auth = HTTPBasicAuth(*self.auth)530-531- # Allow auth to make its changes.532- r = self.auth(self)533-534- # Update self to reflect the auth changes.535- self.__dict__.update(r.__dict__)536-541 _p = urlparse(url)542 no_proxy = filter(lambda x: x.strip(), self.proxies.get('no', '').split(','))543 proxy = self.proxies.get(_p.scheme)544 344 unmodified linesmodified:requests/sessions.py+18 added-29 removed
13 unmodified lines14 from .cookies import cookiejar_from_dict, remove_cookie_by_name15 from .defaults import defaults16 from .models import Request17 from .hooks import dispatch_hook18-from .utils import header_expand, to_key_val_list18+from .utils import header_expand, from_key_val_list19 from .packages.urllib3.poolmanager import PoolManager20 21 22 def merge_kwargs(local_kwarg, default_kwarg):10 unmodified lines33 34 if local_kwarg is None:35 return default_kwarg36 37- kwargs = default_kwarg38- # If default_kwargs is a list rather than a dictionary attempt to convert39- # to dictionary. If the check fails, return local_kwargs.40- if isinstance(default_kwarg, list):41- try:42- kwargs = dict(kwargs)43- except ValueError:44- return local_kwarg45-37 # Bypass if not a dictionary (e.g. timeout)47- if not hasattr(kwargs, 'items'):38+ if not hasattr(default_kwarg, 'items'):39 return local_kwarg40 41+ default_kwarg = from_key_val_list(default_kwarg)50- local_kwarg = to_key_val_list(local_kwarg)42+ local_kwarg = from_key_val_list(local_kwarg)43 44 # Update new values.53- kwargs = kwargs.copy()45+ kwargs = default_kwarg.copy()46 kwargs.update(local_kwarg)47 48 # Remove keys that are set to None.57- for (k, v) in local_kwarg:49+ for (k, v) in local_kwarg.items():50 if v is None:51 del kwargs[k]52 53 return kwargs18 unmodified lines72 prefetch=True,73 verify=True,74 cert=None):75 84- #self.headers = to_key_val_list(headers or [])85- self.headers = headers or {}76+ self.headers = from_key_val_list(headers or [])77 self.auth = auth78 self.timeout = timeout88- self.proxies = to_key_val_list(proxies or [])89- self.hooks = hooks or {}90- self.params = to_key_val_list(params or [])91- self.config = config or {}79+ self.proxies = from_key_val_list(proxies or [])80+ self.hooks = from_key_val_list(hooks or {})81+ self.params = from_key_val_list(params or [])82+ self.config = from_key_val_list(config or {})83 self.prefetch = prefetch84 self.verify = verify85 self.cert = cert86 74 unmodified lines161 # Default empty dicts for dict params.162 data = [] if data is None else data163 files = [] if files is None else files164 headers = {} if headers is None else headers174- params = [] if params is None else params165+ params = {} if params is None else params166 hooks = {} if hooks is None else hooks167 prefetch = prefetch if prefetch is not None else self.prefetch168 169 # use session's hooks as defaults1 unmodified line171 hooks.setdefault(key, cb)172 173 # Expand header values.174 if headers:184- #e = [(k, header_expand(v)) for k, v in to_key_val_list(headers)]185- #headers = e186- for k, v in list(headers.items()) or {}:175+ for k, v in list(headers.items() or {}):176 headers[k] = header_expand(v)177 178 args = dict(179 method=method,180 url=url,181 data=data,193- params=params,194- headers=headers,182+ params=from_key_val_list(params),183+ headers=from_key_val_list(headers),184 cookies=cookies,185 files=files,186 auth=auth,198- hooks=hooks,187+ hooks=from_key_val_list(hooks),188 timeout=timeout,189 allow_redirects=allow_redirects,201- proxies=to_key_val_list(proxies),202- config=config,190+ proxies=from_key_val_list(proxies),191+ config=from_key_val_list(config),192 prefetch=prefetch,193 verify=verify,194 cert=cert,195 _poolmanager=self.poolmanager133 unmodified linesmodified:requests/structures.py+1 added
6 unmodified lines7 Data structures that power Requests.8 9 """10 11+12 class CaseInsensitiveDict(dict):13 """Case-insensitive Dictionary14 15 For example, ``headers['content-encoding']`` will return the52 unmodified linesmodified:requests/utils.py+38 added-17 removed
18 unmodified lines19 from netrc import netrc, NetrcParseError20 21 from . import __version__22 from .compat import parse_http_list as _parse_list_header23-from .compat import quote, urlparse, basestring, bytes, str23+from .compat import quote, urlparse, basestring, bytes, str, OrderedDict24 from .cookies import RequestsCookieJar, cookiejar_from_dict25 26 _hush_pyflakes = (RequestsCookieJar,)27 85 unmodified lines113 if name and name[0] != '<' and name[-1] != '>':114 return name115 116 117+def from_key_val_list(value):118+ """Take an object and test to see if it can be represented as a119+ dictionary. Unless it can not be represented as such, return an120+ OrderedDict, e.g.,121+122+ ::123+124+ >>> from_key_val_list([('key', 'val')])125+ OrderedDict([('key', 'val')])126+ >>> from_key_val_list('string')127+ ValueError: need more than 1 value to unpack128+ >>> from_key_val_list({'key': 'val'})129+ OrderedDict([('key', 'val')])130+ """131+ if value is None:132+ return None133+134+ if isinstance(value, (str, bytes, bool, int)):135+ raise ValueError('cannot encode objects that are not 2-tuples')136+137+ return OrderedDict(value)138+139+140 def to_key_val_list(value):141 """Take an object and test to see if it can be represented as a119- dictionary. Unless it can not be represented as such, return a list of120- tuples, e.g.,:142+ dictionary. If it can be, return a list of tuples, e.g.,143 122- >>> to_key_val_list([('key', 'val')])123- [('key', 'val')]124- >>> to_key_val_list('string')125- ValueError: ...126- >>> to_key_val_list({'key': 'val'})127- [('key', 'val')]144+ ::145+146+ >>> to_key_val_list([('key', 'val')])147+ [('key', 'val')]148+ >>> to_key_val_list({'key': 'val'})149+ [('key', 'val')]150+ >>> to_key_val_list('string')151+ ValueError: cannot encode objects that are not 2-tuples.152 """153 if value is None:154 return None155 132- try:133- dict(value)134- except ValueError:135- raise ValueError('Unable to encode lists with elements that are not '136- '2-tuples.')156+ if isinstance(value, (str, bytes, bool, int)):157+ raise ValueError('cannot encode objects that are not 2-tuples')158 138- if isinstance(value, dict) or hasattr(value, 'items'):159+ if isinstance(value, dict):160 value = value.items()161 162 return list(value)163 387 unmodified lines551 552 i.e. Link: <http:/.../front.jpeg>; rel=front; type="image/jpeg",<http://.../back.jpeg>; rel=back;type="image/jpeg"553 554 """534- 555+556 links = []557 558 replace_chars = " '\""559 11 unmodified lines571 try:572 key,value = param.split("=")573 except ValueError:574 break554- 575+576 link[key.strip(replace_chars)] = value.strip(replace_chars)577 578 links.append(link)579 1 unmodified lineadded:tests/test_proxies.py+27 added
1+#!/usr/bin/env python2+# -*- coding: utf-8 -*-3+4+import sys, os, unittest5+6+# Path hack.7+sys.path.insert(0, os.path.abspath('..'))8+import requests9+10+11+class HTTPSProxyTest(unittest.TestCase):12+ """Smoke test for https functionality."""13+14+ smoke_url = "https://github.com"15+16+ def test_empty_https_proxy(self):17+ proxy = {"https" : "" }18+ result = requests.get(self.smoke_url, verify=False, proxies = proxy)19+ self.assertEqual(result.status_code, 200)20+21+ def test_empty_http_proxy(self):22+ proxy = {"http" : "" }23+ result = requests.get(self.smoke_url, proxies = proxy)24+ self.assertEqual(result.status_code, 200)25+26+if __name__ == '__main__':27+ unittest.main()modified:tests/test_requests.py+5 added-4 removed
1056 unmodified lines1057 1058 def test_prefetch_redirect_bug(self):1059 """Test that prefetch persists across redirections."""1060 res = get(httpbin('redirect/2'), prefetch=False)1061- # prefetch should persist across the redirect; if it doesn't,1062- # this attempt to iterate will crash because the content has already1063- # been read.1061+ # prefetch should persist across the redirect;1062+ # the content should not have been consumed1063+ self.assertFalse(res._content_consumed)1064 first_line = next(res.iter_lines())1065 self.assertTrue(first_line.strip().decode('utf-8').startswith('{'))1066 1067 def test_prefetch_return_response_interaction(self):1068 """Test that prefetch can be overridden as a kwarg to `send`."""1069 req = requests.get(httpbin('get'), return_response=False)1070 req.send(prefetch=False)1071- # content should not have been prefetched, and iter_lines should succeed1071+ # content should not have been prefetched1072+ self.assertFalse(req.response._content_consumed)1073 first_line = next(req.response.iter_lines())1074 self.assertTrue(first_line.strip().decode('utf-8').startswith('{'))1075 1076 def test_accept_objects_with_string_representations_as_urls(self):69 unmodified linesmodified:AUTHORS.rst+1 added
111 unmodified lines112 - Matthias Rahlf <matthias@webding.de>113 - Jakub Roztocil <jakub@roztocil.name>114 - Ian Cordasco <graffatcolmingov@gmail.com> @sigmavirus24115 - Rhys Elsmore116+- André Graf (dergraf)modified:setup.py+2 added
65 unmodified lines66 'Programming Language :: Python :: 3.0',67 'Programming Language :: Python :: 3.1',68 ),69 )70+71+del os.environ['PYTHONDONTWRITEBYTECODE']