Skip to content
Myr

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

12 files+119 added−75 removed

modified:docs/user/advanced.rst+1 added-1 removed
281 unmodified lines
282 import requests283 import json284285 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)287288 for line in r.iter_lines():289 if line: # filter out keep-alive new lines290 print json.loads(line)
271 unmodified lines
modified:docs/user/intro.rst+2 added-6 removed
15 unmodified lines
16#. Readability counts.1718All contributions to Requests should keep these important rules in mind.1920.. _`isc`:2122ISC License23-----------24
16 unmodified lines
4142Requests License43----------------4444 Copyright (c) 2011, Kenneth Reitz4546 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.4748 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.4945 .. include:: ../../LICENSE
modified:requests/compat.py+2 added
91 unmodified lines
92 try:93 import cchardet as chardet94 except ImportError:95 from .packages import chardet96 from .packages.urllib3.packages.ordered_dict import OrderedDict9798 builtin_str = str99 bytes = str100 str = unicode
8 unmodified lines
109 from http import cookiejar as cookielib110 from http.cookies import Morsel111 from io import StringIO112 from .packages import chardet2 as chardet113 from collections import OrderedDict114115 builtin_str = str116 str = str117 bytes = bytes
2 unmodified lines
modified:requests/defaults.py+1 added-1 removed
18 unmodified lines
19: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.2425"""2627SCHEMAS = ['http', 'https']
23 unmodified lines
modified:requests/models.py+21 added-17 removed
32 unmodified lines
33 stream_decode_response_unicode, get_netrc_auth, get_environ_proxies,34 to_key_val_list, DEFAULT_CA_BUNDLE_PATH, parse_header_links, iter_slices)35from .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)3839REDIRECT_STATI = (codes.moved, codes.found, codes.other, codes.temporary_moved)40CONTENT_CHUNK_SIZE = 10 * 102441
68 unmodified lines
110111 # Dictionary mapping protocol to the URL of the proxy (e.g. {'http': 'foo.bar:3128'})112 self.proxies = dict(proxies or [])113114 for proxy_type,uri_ref in list(self.proxies.items()):115 if not uri_ref:116 del self.proxies[proxy_type]117118 # 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 lines
196 # Fallback to None if there's no status_code, for whatever reason.197 response.status_code = getattr(resp, 'status', None)198199 # Make headers case-insensitive.196 response.headers = CaseInsensitiveDict(getattr(resp, 'headers', None))200 response.headers = CaseInsensitiveDict(getattr(resp, 'headers', {}))201202 # Set encoding.203 response.encoding = get_encoding_from_headers(response.headers)204
297 unmodified lines
502 self.config.get('verbose').write('%s %s %s\n' % (503 datetime.now().isoformat(), self.method, url504 ))505506 # 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)509510 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)514515 # Allow auth to make its changes.516 r = self.auth(self)517518 # Update self to reflect the auth changes.519 self.__dict__.update(r.__dict__)520521 # Nottin' on you.522 body = None523 content_type = None524
12 unmodified lines
537 # 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_type540522 # 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)525526 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)530531 # Allow auth to make its changes.532 r = self.auth(self)533534 # Update self to reflect the auth changes.535 self.__dict__.update(r.__dict__)536541 _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 lines
modified:requests/sessions.py+18 added-29 removed
13 unmodified lines
14from .cookies import cookiejar_from_dict, remove_cookie_by_name15from .defaults import defaults16from .models import Request17from .hooks import dispatch_hook18from .utils import header_expand, to_key_val_list18from .utils import header_expand, from_key_val_list19from .packages.urllib3.poolmanager import PoolManager202122def merge_kwargs(local_kwarg, default_kwarg):
10 unmodified lines
3334 if local_kwarg is None:35 return default_kwarg3637 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_kwarg4537 # Bypass if not a dictionary (e.g. timeout)47 if not hasattr(kwargs, 'items'):38 if not hasattr(default_kwarg, 'items'):39 return local_kwarg4041 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)4344 # Update new values.53 kwargs = kwargs.copy()45 kwargs = default_kwarg.copy()46 kwargs.update(local_kwarg)4748 # 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]5253 return kwargs
18 unmodified lines
72 prefetch=True,73 verify=True,74 cert=None):7584 #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 lines
161 # 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.prefetch168169 # use session's hooks as defaults
1 unmodified line
171 hooks.setdefault(key, cb)172173 # 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)177178 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.poolmanager
133 unmodified lines
modified:requests/structures.py+1 added
6 unmodified lines
7Data structures that power Requests.89"""101112class CaseInsensitiveDict(dict):13 """Case-insensitive Dictionary1415 For example, ``headers['content-encoding']`` will return the
52 unmodified lines
modified:requests/utils.py+38 added-17 removed
18 unmodified lines
19from netrc import netrc, NetrcParseError2021from . import __version__22from .compat import parse_http_list as _parse_list_header23from .compat import quote, urlparse, basestring, bytes, str23from .compat import quote, urlparse, basestring, bytes, str, OrderedDict24from .cookies import RequestsCookieJar, cookiejar_from_dict2526_hush_pyflakes = (RequestsCookieJar,)27
85 unmodified lines
113 if name and name[0] != '<' and name[-1] != '>':114 return name115116117def 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.,121122 ::123124 >>> 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 None133134 if isinstance(value, (str, bytes, bool, int)):135 raise ValueError('cannot encode objects that are not 2-tuples')136137 return OrderedDict(value)138139140def 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.,143122 >>> 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 ::145146 >>> 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 None155132 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')158138 if isinstance(value, dict) or hasattr(value, 'items'):159 if isinstance(value, dict):160 value = value.items()161162 return list(value)163
387 unmodified lines
551552 i.e. Link: <http:/.../front.jpeg>; rel=front; type="image/jpeg",<http://.../back.jpeg>; rel=back;type="image/jpeg"553554 """534 555556 links = []557558 replace_chars = " '\""559
11 unmodified lines
571 try:572 key,value = param.split("=")573 except ValueError:574 break554 575576 link[key.strip(replace_chars)] = value.strip(replace_chars)577578 links.append(link)579
1 unmodified line
added:tests/test_proxies.py+27 added
1#!/usr/bin/env python2# -*- coding: utf-8 -*-34import sys, os, unittest56# Path hack.7sys.path.insert(0, os.path.abspath('..'))8import requests91011class HTTPSProxyTest(unittest.TestCase):12 """Smoke test for https functionality."""1314 smoke_url = "https://github.com"1516 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)2021 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)2526if __name__ == '__main__':27 unittest.main()
modified:tests/test_requests.py+5 added-4 removed
1056 unmodified lines
10571058 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('{'))10661067 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('{'))10751076 def test_accept_objects_with_string_representations_as_urls(self):
69 unmodified lines
modified:AUTHORS.rst+1 added
111 unmodified lines
112- 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 lines
66 'Programming Language :: Python :: 3.0',67 'Programming Language :: Python :: 3.1',68 ),69)7071del os.environ['PYTHONDONTWRITEBYTECODE']