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 a1b6ef3, 2dccc8e · Browse files · 11 files·+157 added−40 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
11 files+157 added−40 removed
- tests:+61 added−2 removed
- other:+96 added−38 removed
Provenance
- Commit
7fea9af- Tree
4a7f112- Author
Kenneth Reitz <me@kennethreitz.com>- Committer
Kenneth Reitz <me@kennethreitz.com>- Parent 1
a1b6ef3- Parent 2
2dccc8e
11 files changed+157 added−40 removed
modified:docs/dev/todo.rst+13 added-1 removed
21 unmodified lines22 $ . env/bin/activate23 $ make24 $ make test25 26-The ``Makefile`` has various useful targets for testing.26+The ``Makefile`` has various useful targets for testing. For example, if you 27+want to see how your pull request will behave with Travis-CI you would run 28+``make travis``.29 30+Versions of Python to Test On31+-----------------------------32+33+Officially (as of 26-Nov-2012), requests supports python 2.6-3.3. In the 34+future, support for 3.1 and 3.2 may be dropped. In general you will need to 35+test on at least one python 2 and one python 3 version. You can also set up 36+Travis CI for your own fork before you submit a pull request so that you are 37+assured your fork works. To use Travis CI for your fork and other projects see 38+their `documentation <http://about.travis-ci.org/docs/user/getting-started/>`_.39+40 What Needs to be Done41 ---------------------42 43 - Documentation needs a roadmap.modified:requests/api.py-2 removed
10 unmodified lines11 12 """13 14 from . import sessions15-from .safe_mode import catch_exceptions_if_in_safe_mode15 16 18-@catch_exceptions_if_in_safe_mode17 def request(method, url, **kwargs):18 """Constructs and sends a :class:`Request <Request>`.19 Returns :class:`Response <Response>` object.20 108 unmodified linesmodified:requests/auth.py+22 added-8 removed
90 unmodified lines91 if r.files and contenttype == CONTENT_TYPE_MULTI_PART:92 # Omit body data in the signing and since it will always93 # be empty (cant add paras to body if multipart) and we wish94 # to preserve body.95- r.url, r.headers, _ = self.client.sign(96- unicode(r.full_url), unicode(r.method), None, r.headers)97- elif decoded_body is not None and contenttype in (CONTENT_TYPE_FORM_URLENCODED, ''):98- # Normal signing99- if not contenttype:100- r.headers['Content-Type'] = CONTENT_TYPE_FORM_URLENCODED101- r.url, r.headers, r.data = self.client.sign(102- unicode(r.full_url), unicode(r.method), r.data, r.headers)95+ r.url, r.headers, _ = self.client.sign(unicode(r.full_url),96+ unicode(r.method),97+ None,98+ r.headers)99+ elif (decoded_body is not None and 100+ contenttype == CONTENT_TYPE_FORM_URLENCODED):101+ # If the Content-Type header is urlencoded and there are no102+ # illegal characters in the body, assume that the content actually103+ # is urlencoded, and so should be part of the signature.104+ r.url, r.headers, r.data = self.client.sign(unicode(r.full_url),105+ unicode(r.method),106+ r.data,107+ r.headers)108+ elif r.data:109+ # The data we passed was either definitely not urlencoded110+ # (because extract_params returned nothing) or doesn't have a111+ # content header that assures us that it is. Assume then that the112+ # data shouldn't be part of the signature.113+ r.url, r.headers, _ = self.client.sign(unicode(r.full_url),114+ unicode(r.method),115+ None,116+ r.headers)117 else:118 _oauth_signed = False119 if _oauth_signed:120 # Both flows add params to the URL by using r.full_url,276 unmodified linesmodified:requests/cookies.py+2 added-1 removed
30 unmodified lines31 32 def __init__(self, request):33 self._r = request34 self._new_headers = {}35+ self.type = urlparse(self._r.full_url).scheme36 37 def get_type(self):37- return urlparse(self._r.full_url).scheme38+ return self.type39 40 def get_host(self):41 return urlparse(self._r.full_url).netloc42 336 unmodified linesmodified:requests/models.py+12 added-3 removed
7 unmodified lines8 """9 10 import os11 import socket12+import collections13 from datetime import datetime14 from io import BytesIO15 16 from .hooks import dispatch_hook, HOOKS102 unmodified lines119 120 # If no proxies are given, allow configuration by environment variables121 # HTTP_PROXY and HTTPS_PROXY.122 if not self.proxies and self.config.get('trust_env'):122- self.proxies = get_environ_proxies()123+ self.proxies = get_environ_proxies(self.url)124 125 self.data = data126 self.params = params127 self.files = files339 unmodified lines467 return ''.join(url)468 469 def register_hook(self, event, hook):470 """Properly register a hook."""470- if callable(hook):471+ if isinstance(hook, collections.Callable):472 self.hooks[event].append(hook)473 elif hasattr(hook, '__iter__'):473- self.hooks[event].extend(h for h in hook if callable(h))474+ self.hooks[event].extend(h for h in hook if isinstance(h, collections.Callable))475 476 def deregister_hook(self, event, hook):477 """Deregister a previously registered hook.478 Returns True if the hook existed, False if not.62 unmodified lines541 content_type = None542 else:543 content_type = 'application/x-www-form-urlencoded'544 545+ self.headers['Content-Length'] = '0'546+ if hasattr(body, 'seek') and hasattr(body, 'tell'):547+ body.seek(0, 2)548+ self.headers['Content-Length'] = str(body.tell())549+ body.seek(0, 0)550+ elif body is not None:551+ self.headers['Content-Length'] = str(len(body))552+553 # Add content-type if it wasn't explicitly provided.554 if (content_type) and (not 'content-type' in self.headers):555 self.headers['Content-Type'] = content_type556 362 unmodified linesmodified:requests/safe_mode.py+5 added-5 removed
16 unmodified lines17 import socket18 19 20 def catch_exceptions_if_in_safe_mode(function):21- """New implementation of safe_mode. We catch all exceptions at the API level21+ """New implementation of safe_mode. We catch all exceptions at the Session level22 and then return a blank Response object with the error field filled. This decorator23- wraps request() in api.py.23+ wraps Session._send_request() in sessions.py.24 """25 26- def wrapped(method, url, **kwargs):26+ def wrapped(*args, **kwargs):27 # if save_mode, we catch exceptions and fill error field28 if (kwargs.get('config') and kwargs.get('config').get('safe_mode')) or (kwargs.get('session')29 and kwargs.get('session').config.get('safe_mode')):30 try:31- return function(method, url, **kwargs)31+ return function(*args, **kwargs)32 except (RequestException, ConnectionError, HTTPError,33 socket.timeout, socket.gaierror) as e:34 r = Response()35 r.error = e36 r.raw = HTTPResponse() # otherwise, tests fail37 r.status_code = 0 # with this status_code, content returns None38 return r39- return function(method, url, **kwargs)39+ return function(*args, **kwargs)40 return wrappedmodified:requests/sessions.py+7 added-1 removed
15 unmodified lines16 from .models import Request17 from .hooks import dispatch_hook18 from .utils import header_expand, from_key_val_list19 from .packages.urllib3.poolmanager import PoolManager20+from .safe_mode import catch_exceptions_if_in_safe_mode21 22 23 def merge_kwargs(local_kwarg, default_kwarg):24 """Merges kwarg dictionaries.240 unmodified lines265 if not return_response:266 return r267 268 # Send the HTTP Request.268- r.send(prefetch=prefetch)269+ return self._send_request(r, **args)270 271+ @catch_exceptions_if_in_safe_mode272+ def _send_request(self, r, **kwargs):273+ # Send the request.274+ r.send(prefetch=kwargs.get("prefetch"))275+276 # Return the response.277 return r.response278 279 def get(self, url, **kwargs):82 unmodified linesmodified:requests/utils.py+34 added-17 removed
27 unmodified lines28 CERTIFI_BUNDLE_PATH = None29 try:30 # see if requests's own CA certificate bundle is installed31 from . import certs32+ path = certs.where()33+ if os.path.exists(path):32- CERTIFI_BUNDLE_PATH = certs.where()34+ CERTIFI_BUNDLE_PATH = certs.where()35 except ImportError:36 pass37 38 NETRC_FILES = ('.netrc', '_netrc')435 unmodified lines474 def unquote_unreserved(uri):475 """Un-escape any percent-escape sequences in a URI that are unreserved476 characters. This leaves all reserved, illegal and non-ASCII bytes encoded.477 """476- try:477- parts = uri.split('%')478- for i in range(1, len(parts)):479- h = parts[i][0:2]480- if len(h) == 2 and h.isalnum():481- c = chr(int(h, 16))482- if c in UNRESERVED_SET:483- parts[i] = c + parts[i][2:]478+ parts = uri.split('%')479+ for i in range(1, len(parts)):480+ h = parts[i][0:2]481+ if len(h) == 2 and h.isalnum():482+ c = chr(int(h, 16))483+ if c in UNRESERVED_SET:484+ parts[i] = c + parts[i][2:]484- else:485- parts[i] = '%' + parts[i]485 else:486 parts[i] = '%' + parts[i]488- return ''.join(parts)489- except ValueError:490- return uri487+ else:488+ parts[i] = '%' + parts[i]489+ return ''.join(parts)490 491 492 def requote_uri(uri):493 """Re-quote the given URI.6 unmodified lines500 # or '%')501 return quote(unquote_unreserved(uri), safe="!#$%&'()*+,/:;=?@[]~")502 503 505-def get_environ_proxies():504+def get_environ_proxies(url):505 """Return a dict of environment proxies."""506 507 proxy_keys = [508 'all',509 'http',510 'https',511 'ftp',513- 'socks',514- 'no'512+ 'socks'513 ]514 515 get_proxy = lambda k: os.environ.get(k) or os.environ.get(k.upper())516+517+ # First check whether no_proxy is defined. If it is, check that the URL518+ # we're getting isn't in the no_proxy list.519+ no_proxy = get_proxy('no_proxy')520+521+ if no_proxy:522+ # We need to check whether we match here. We need to see if we match523+ # the end of the netloc, both with and without the port.524+ no_proxy = no_proxy.split(',')525+ netloc = urlparse(url).netloc526+527+ for host in no_proxy:528+ if netloc.endswith(host) or netloc.split(':')[0].endswith(host):529+ # The URL does match something in no_proxy, so we don't want530+ # to apply the proxies on this URL.531+ return {}532+533+ # If we get here, we either didn't have no_proxy set or we're not going534+ # anywhere that no_proxy applies to.535 proxies = [(key, get_proxy(key + '_proxy')) for key in proxy_keys]536 return dict([(key, val) for (key, val) in proxies if val])537 538 102 unmodified linesmodified:tests/test_requests.py+15 added-1 removed
9 unmodified lines10 import json11 import unittest12 import pickle13 import tempfile14+import collections15 16 import requests17 from requests.compat import str, StringIO18 # import envoy786 unmodified lines805 return args806 807 def assert_hooks_are_callable(hooks):808 for h in hooks['args']:808- self.assertTrue(callable(h))809+ self.assertTrue(isinstance(h, collections.Callable))810 811 hooks = [add_foo_header, add_bar_header]812 r = requests.models.Request()813 r.register_hook('args', hooks)115 unmodified lines929 ds1 = pickle.loads(pickle.dumps(requests.session()))930 ds2 = pickle.loads(pickle.dumps(requests.session(prefetch=False)))931 self.assertTrue(ds1.prefetch)932 self.assertFalse(ds2.prefetch)933+ 934+ def test_session_connection_error_with_safe_mode(self):935+ config = {"safe_mode":True}936 937+ s = requests.session()938+ r = s.get("http://localhost:1/nope", timeout=0.1, config=config)939+ self.assertFalse(r.ok)940+ self.assertTrue(r.content is None)941+942+ s2 = requests.session(config=config)943+ r2 = s2.get("http://localhost:1/nope", timeout=0.1)944+ self.assertFalse(r2.ok)945+ self.assertTrue(r2.content is None)946+947 def test_connection_error(self):948 try:949 get('http://localhost:1/nope')950 except requests.ConnectionError:284 unmodified linesmodified:tests/test_utils.py+46 added-1 removed
7 unmodified lines8 import random9 10 # Path hack.11 sys.path.insert(0, os.path.abspath('..'))12+from requests.utils import get_environ_proxies13 import requests.utils14 from requests.compat import is_py3, bytes15 16 3 unmodified lines20 else:21 byteschr = chr22 23 23-class GuessJSONUTFTests(unittest.TestCase):24+class UtilityTests(unittest.TestCase):25 """Tests for the JSON UTF encoding guessing code."""26 27 codecs = (28 'utf-8', 'utf-8-sig',44 unmodified lines73 # see the need; we are not testing UTF decoding here.74 continue75 raise76 77+ def test_get_environ_proxies_respects_no_proxy(self):78+ '''This test confirms that the no_proxy environment setting is79+ respected by get_environ_proxies().'''80+81+ # Store the current environment settings.82+ try:83+ old_http_proxy = os.environ['http_proxy']84+ except KeyError:85+ old_http_proxy = None86+87+ try:88+ old_no_proxy = os.environ['no_proxy']89+ except KeyError:90+ old_no_proxy = None91+92+ # Set up some example environment settings.93+ os.environ['http_proxy'] = 'http://www.example.com/'94+ os.environ['no_proxy'] = r'localhost,.0.0.1:8080'95+96+ # Set up expected proxy return values.97+ proxy_yes = {'http': 'http://www.example.com/'}98+ proxy_no = {}99+100+ # Check that we get the right things back.101+ self.assertEqual(proxy_yes,102+ get_environ_proxies('http://www.google.com/'))103+ self.assertEqual(proxy_no,104+ get_environ_proxies('http://localhost/test'))105+ self.assertEqual(proxy_no,106+ get_environ_proxies('http://127.0.0.1:8080/'))107+ self.assertEqual(proxy_yes,108+ get_environ_proxies('http://127.0.0.1:8081/'))109+110+ # Return the settings to what they were.111+ if old_http_proxy:112+ os.environ['http_proxy'] = old_http_proxy113+ else:114+ del os.environ['http_proxy']115+116+ if old_no_proxy:117+ os.environ['no_proxy'] = old_no_proxy118+ else:119+ del os.environ['no_proxy']120+121 if __name__ == '__main__':122 unittest.main()modified:AUTHORS.rst+1 added
114 unmodified lines115 - Rhys Elsmore116 - André Graf (dergraf)117 - Stephen Zhuang (everbird)118 - Martijn Pieters119+- Jonatan Heyman