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 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

11 files+157 added−40 removed

modified:docs/dev/todo.rst+13 added-1 removed
21 unmodified lines
22 $ . env/bin/activate23 $ make24 $ make test2526The ``Makefile`` has various useful targets for testing.26The ``Makefile`` has various useful targets for testing. For example, if you 27want to see how your pull request will behave with Travis-CI you would run 28``make travis``.2930Versions of Python to Test On31-----------------------------3233Officially (as of 26-Nov-2012), requests supports python 2.6-3.3. In the 34future, support for 3.1 and 3.2 may be dropped. In general you will need to 35test on at least one python 2 and one python 3 version. You can also set up 36Travis CI for your own fork before you submit a pull request so that you are 37assured your fork works. To use Travis CI for your fork and other projects see 38their `documentation <http://about.travis-ci.org/docs/user/getting-started/>`_.3940What Needs to be Done41---------------------4243- Documentation needs a roadmap.
modified:requests/api.py-2 removed
10 unmodified lines
1112"""1314from . import sessions15from .safe_mode import catch_exceptions_if_in_safe_mode151618@catch_exceptions_if_in_safe_mode17def request(method, url, **kwargs):18 """Constructs and sends a :class:`Request <Request>`.19 Returns :class:`Response <Response>` object.20
108 unmodified lines
modified:requests/auth.py+22 added-8 removed
90 unmodified lines
91 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 lines
modified:requests/cookies.py+2 added-1 removed
30 unmodified lines
3132 def __init__(self, request):33 self._r = request34 self._new_headers = {}35 self.type = urlparse(self._r.full_url).scheme3637 def get_type(self):37 return urlparse(self._r.full_url).scheme38 return self.type3940 def get_host(self):41 return urlparse(self._r.full_url).netloc42
336 unmodified lines
modified:requests/models.py+12 added-3 removed
7 unmodified lines
8"""910import os11import socket12import collections13from datetime import datetime14from io import BytesIO1516from .hooks import dispatch_hook, HOOKS
102 unmodified lines
119120 # 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)124125 self.data = data126 self.params = params127 self.files = files
339 unmodified lines
467 return ''.join(url)468469 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))475476 def deregister_hook(self, event, hook):477 """Deregister a previously registered hook.478 Returns True if the hook existed, False if not.
62 unmodified lines
541 content_type = None542 else:543 content_type = 'application/x-www-form-urlencoded'544545 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))552553 # 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 lines
modified:requests/safe_mode.py+5 added-5 removed
16 unmodified lines
17import socket181920def 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 """2526 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 wrapped
modified:requests/sessions.py+7 added-1 removed
15 unmodified lines
16from .models import Request17from .hooks import dispatch_hook18from .utils import header_expand, from_key_val_list19from .packages.urllib3.poolmanager import PoolManager20from .safe_mode import catch_exceptions_if_in_safe_mode212223def merge_kwargs(local_kwarg, default_kwarg):24 """Merges kwarg dictionaries.
240 unmodified lines
265 if not return_response:266 return r267268 # Send the HTTP Request.268 r.send(prefetch=prefetch)269 return self._send_request(r, **args)270271 @catch_exceptions_if_in_safe_mode272 def _send_request(self, r, **kwargs):273 # Send the request.274 r.send(prefetch=kwargs.get("prefetch"))275276 # Return the response.277 return r.response278279 def get(self, url, **kwargs):
82 unmodified lines
modified:requests/utils.py+34 added-17 removed
27 unmodified lines
28CERTIFI_BUNDLE_PATH = None29try: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()35except ImportError:36 pass3738NETRC_FILES = ('.netrc', '_netrc')
435 unmodified lines
474def 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)490491492def requote_uri(uri):493 """Re-quote the given URI.
6 unmodified lines
500 # or '%')501 return quote(unquote_unreserved(uri), safe="!#$%&'()*+,/:;=?@[]~")502503505def get_environ_proxies():504def get_environ_proxies(url):505 """Return a dict of environment proxies."""506507 proxy_keys = [508 'all',509 'http',510 'https',511 'ftp',513 'socks',514 'no'512 'socks'513 ]514515 get_proxy = lambda k: os.environ.get(k) or os.environ.get(k.upper())516517 # 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')520521 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).netloc526527 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 {}532533 # 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])537538
102 unmodified lines
modified:tests/test_requests.py+15 added-1 removed
9 unmodified lines
10import json11import unittest12import pickle13import tempfile14import collections1516import requests17from requests.compat import str, StringIO18# import envoy
786 unmodified lines
805 return args806807 def assert_hooks_are_callable(hooks):808 for h in hooks['args']:808 self.assertTrue(callable(h))809 self.assertTrue(isinstance(h, collections.Callable))810811 hooks = [add_foo_header, add_bar_header]812 r = requests.models.Request()813 r.register_hook('args', hooks)
115 unmodified lines
929 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}936937 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)941942 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)946947 def test_connection_error(self):948 try:949 get('http://localhost:1/nope')950 except requests.ConnectionError:
284 unmodified lines
modified:tests/test_utils.py+46 added-1 removed
7 unmodified lines
8import random910# Path hack.11sys.path.insert(0, os.path.abspath('..'))12from requests.utils import get_environ_proxies13import requests.utils14from requests.compat import is_py3, bytes1516
3 unmodified lines
20else:21 byteschr = chr222323class GuessJSONUTFTests(unittest.TestCase):24class UtilityTests(unittest.TestCase):25 """Tests for the JSON UTF encoding guessing code."""2627 codecs = (28 'utf-8', 'utf-8-sig',
44 unmodified lines
73 # see the need; we are not testing UTF decoding here.74 continue75 raise7677 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().'''8081 # Store the current environment settings.82 try:83 old_http_proxy = os.environ['http_proxy']84 except KeyError:85 old_http_proxy = None8687 try:88 old_no_proxy = os.environ['no_proxy']89 except KeyError:90 old_no_proxy = None9192 # 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'9596 # Set up expected proxy return values.97 proxy_yes = {'http': 'http://www.example.com/'}98 proxy_no = {}99100 # 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/'))109110 # 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']115116 if old_no_proxy:117 os.environ['no_proxy'] = old_no_proxy118 else:119 del os.environ['no_proxy']120121if __name__ == '__main__':122 unittest.main()
modified:AUTHORS.rst+1 added
114 unmodified lines
115- Rhys Elsmore116- André Graf (dergraf)117- Stephen Zhuang (everbird)118- Martijn Pieters119- Jonatan Heyman