Whitespace fixes following PEP8.
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by Locker537 · committed by Locker537 · parent 4130cf9 · Browse files · 17 files·+67 added−47 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
17 files+67 added−47 removed
- tests:+18 added−22 removed
- other:+49 added−25 removed
Provenance
- Commit
42d0a21- Tree
b998153- Author
Locker537 <locker537@gmail.com>- Committer
Locker537 <locker537@gmail.com>- Parent
4130cf9
17 files changed+67 added−47 removed
modified:requests/api.py+2 added
12 unmodified lines13 14 from . import sessions15 from .safe_mode import catch_exceptions_if_in_safe_mode16 17+18 @catch_exceptions_if_in_safe_mode19 def request(method, url, **kwargs):20 """Constructs and sends a :class:`Request <Request>`.21 Returns :class:`Response <Response>` object.30 unmodified lines52 finally:53 if adhoc_session:54 session.close()55 56+57 def get(url, **kwargs):58 """Sends a GET request. Returns :class:`Response` object.59 60 :param url: URL for the new :class:`Request` object.70 unmodified linesmodified:requests/auth.py+3 added
32 unmodified lines33 log = logging.getLogger(__name__)34 35 CONTENT_TYPE_FORM_URLENCODED = 'application/x-www-form-urlencoded'36 37+38 def _basic_auth_str(username, password):39 """Returns a Basic Auth string."""40 41 return 'Basic ' + b64encode(('%s:%s' % (username, password)).encode('latin1')).strip().decode('latin1')197 unmodified lines239 def __call__(self, r):240 r.register_hook('response', self.handle_401)241 return r242 243+244 def _negotiate_value(r):245 """Extracts the gssapi authentication token from the appropriate header"""246 247 authreq = r.headers.get('www-authenticate', None)5 unmodified lines253 return mo.group(1)254 255 return None256 257+258 class HTTPKerberosAuth(AuthBase):259 """Attaches HTTP GSSAPI/Kerberos Authentication to the given Request object."""260 def __init__(self, require_mutual_auth=True):261 if k is None:103 unmodified linesmodified:requests/compat.py-1 removed
110 unmodified lines111 str = str112 bytes = bytes113 basestring = (str,bytes)114 numeric_types = (int, float)115-modified:requests/cookies.py+20 added-10 removed
12 unmodified lines13 threading14 except ImportError:15 import dummy_threading as threading16 17+18 class MockRequest(object):19 """Wraps a `requests.Request` to mimic a `urllib2.Request`.20 21 The code in `cookielib.CookieJar` expects this interface in order to correctly44 unmodified lines66 67 def get_new_headers(self):68 return self._new_headers69 70+71 class MockResponse(object):72 """Wraps a `httplib.HTTPMessage` to mimic a `urllib.addinfourl`.73 74 ...what? Basically, expose the parsed HTTP headers from the server response12 unmodified lines87 88 def getheaders(self, name):89 self._headers.getheaders(name)90 91+92 def extract_cookies_to_jar(jar, request, response):93 """Extract the cookies from the response into a CookieJar.94 95 :param jar: cookielib.CookieJar (not necessarily a RequestsCookieJar)5 unmodified lines101 # pull out the HTTPMessage with the headers and put it in the mock:102 res = MockResponse(response._original_response.msg)103 jar.extract_cookies(res, req)104 105+106 def get_cookie_header(jar, request):107 """Produce an appropriate Cookie header string to be sent with `request`, or None."""108 r = MockRequest(request)109 jar.add_cookie_header(r)110 return r.get_new_headers().get('Cookie')111 112+113 def remove_cookie_by_name(cookiejar, name, domain=None, path=None):114 """Unsets a cookie by name, by default over all domains and paths.115 116 Wraps CookieJar.clear(), is O(n).7 unmodified lines124 125 for domain, path, name in clearables:126 cookiejar.clear(domain, path, name)127 128+129 class CookieConflictError(RuntimeError):124- """There are two cookies that meet the criteria specified in the cookie jar. 130+ """There are two cookies that meet the criteria specified in the cookie jar.131 Use .get and .set and include domain and path args in order to be more specific."""132 133+134 class RequestsCookieJar(cookielib.CookieJar, collections.MutableMapping):135 """Compatibility class; is a cookielib.CookieJar, but exposes a dict interface.136 137 This is the CookieJar we create by default for requests and sessions that49 unmodified lines187 values = []188 for cookie in iter(self):189 values.append(cookie.value)190 return values184- 191+192 def items(self):193 """Dict-like items() that returns a list of name-value tuples from the jar.194 See keys() and values(). Allows client-code to call "dict(RequestsCookieJar)195 and get a vanilla python dict of key value pairs."""25 unmodified lines221 for cookie in iter(self):222 if cookie.domain is not None and cookie.domain in domains:223 return True224 domains.append(cookie.domain)218- return False # there is only one domain in jar225+ return False # there is only one domain in jar226 227 def get_dict(self, domain=None, path=None):228 """Takes as an argument an optional domain and path and returns a plain old229 Python dict of name-value pairs of cookies that meet the requirements."""230 dictionary = {}231 for cookie in iter(self):225- if (domain == None or cookie.domain == domain) and (path == None 232+ if (domain == None or cookie.domain == domain) and (path == None233 or cookie.path == path):234 dictionary[cookie.name] = cookie.value235 return dictionary236 13 unmodified lines250 """Deletes a cookie given a name. Wraps cookielib.CookieJar's remove_cookie_by_name()."""251 remove_cookie_by_name(self, name)252 253 def _find(self, name, domain=None, path=None):247- """Requests uses this method internally to get cookie values. Takes as args name 254+ """Requests uses this method internally to get cookie values. Takes as args name255 and optional domain and path. Returns a cookie.value. If there are conflicting cookies,256 _find arbitrarily chooses one. See _find_no_duplicates if you want an exception thrown257 if there are conflicting cookies."""258 for cookie in iter(self):4 unmodified lines263 264 raise KeyError('name=%r, domain=%r, path=%r' % (name, domain, path))265 266 def _find_no_duplicates(self, name, domain=None, path=None):260- """__get_item__ and get call _find_no_duplicates -- never used in Requests internally. 261- Takes as args name and optional domain and path. Returns a cookie.value. 262- Throws KeyError if cookie is not found and CookieConflictError if there are 267+ """__get_item__ and get call _find_no_duplicates -- never used in Requests internally.268+ Takes as args name and optional domain and path. Returns a cookie.value.269+ Throws KeyError if cookie is not found and CookieConflictError if there are270 multiple cookies that match name and optionally domain and path."""271 toReturn = None272 for cookie in iter(self):273 if cookie.name == name:274 if domain is None or cookie.domain == domain:275 if path is None or cookie.path == path:269- if toReturn != None: # if there are multiple cookies that meet passed in criteria276+ if toReturn != None: # if there are multiple cookies that meet passed in criteria277 raise CookieConflictError('There are multiple cookies with name, %r' % (name))271- toReturn = cookie.value # we will eventually return this as long as no cookie conflict278+ toReturn = cookie.value # we will eventually return this as long as no cookie conflict279 280 if toReturn:281 return toReturn282 raise KeyError('name=%r, domain=%r, path=%r' % (name, domain, path))14 unmodified lines297 def copy(self):298 """This is not implemented. Calling this will throw an exception."""299 raise NotImplementedError300 301+302 def create_cookie(name, value, **kwargs):303 """Make a cookie from underspecified parameters.304 305 By default, the pair of `name` and `value` will be set for the domain ''27 unmodified lines333 result['path_specified'] = bool(result['path'])334 335 return cookielib.Cookie(**result)336 337+338 def morsel_to_cookie(morsel):339 """Convert a Morsel object into a Cookie containing the one k/v pair."""340 c = create_cookie(341 name=morsel.key,15 unmodified lines357 rfc2109=False,358 )359 return c360 361+362 def cookiejar_from_dict(cookie_dict, cookiejar=None):363 """Returns a CookieJar from a key/value dictionary.364 365 :param cookie_dict: Dict of key/values to insert into CookieJar.8 unmodified linesmodified:requests/exceptions.py+10 added
6 unmodified lines7 This module contains the set of Requests' exceptions.8 9 """10 11+12 class RequestException(RuntimeError):13 """There was an ambiguous exception that occurred while handling your14 request."""15 16+17 class HTTPError(RequestException):18 """An HTTP error occurred."""19 response = None20 21+22 class ConnectionError(RequestException):23 """A Connection error occurred."""24 25+26 class SSLError(ConnectionError):27 """An SSL error occurred."""28 29+30 class Timeout(RequestException):31 """The request timed out."""32 33+34 class URLRequired(RequestException):35 """A valid URL is required to make a request."""36 37+38 class TooManyRedirects(RequestException):39 """Too many redirects."""40 41+42 class MissingSchema(RequestException, ValueError):43 """The URL schema (e.g. http or https) is missing."""44 45+46 class InvalidSchema(RequestException, ValueError):47 """See defaults.py for valid schemas."""48 49+50 class InvalidURL(RequestException, ValueError):51 """ The URL provided was somehow invalid. """modified:requests/hooks.py+1 added
28 unmodified lines29 30 31 HOOKS = ('args', 'pre_request', 'pre_send', 'post_request', 'response')32 33+34 def dispatch_hook(key, hooks, hook_data):35 """Dispatches a hook dictionary on a given piece of data."""36 37 hooks = hooks or dict()17 unmodified linesmodified:requests/models.py+2 added-1 removed
37 unmodified lines38 39 REDIRECT_STATI = (codes.moved, codes.found, codes.other, codes.temporary_moved)40 CONTENT_CHUNK_SIZE = 10 * 102441 42+43 class Request(object):44 """The :class:`Request <Request>` object. It carries out all functionality of45 Requests. Recommended interface is with the Requests functions.46 """506 unmodified lines553 # Update self to reflect the auth changes.554 self.__dict__.update(r.__dict__)555 556 _p = urlparse(url)556- no_proxy = filter(lambda x:x.strip(), self.proxies.get('no', '').split(','))557+ no_proxy = filter(lambda x: x.strip(), self.proxies.get('no', '').split(','))558 proxy = self.proxies.get(_p.scheme)559 560 if proxy and not any(map(_p.netloc.endswith, no_proxy)):561 conn = poolmanager.proxy_from_url(proxy)325 unmodified linesmodified:requests/safe_mode.py+5 added-4 removed
14 unmodified lines15 from .packages.urllib3.response import HTTPResponse16 from .exceptions import RequestException, ConnectionError, HTTPError17 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 level22 and then return a blank Response object with the error field filled. This decorator23 wraps request() in api.py.24 """24- 25+26 def wrapped(method, url, **kwargs):27 # if save_mode, we catch exceptions and fill error field27- if (kwargs.get('config') and kwargs.get('config').get('safe_mode')) or (kwargs.get('session') 28+ 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)32 except (RequestException, ConnectionError, HTTPError,33 socket.timeout, socket.gaierror) as e:34 r = Response()35 r.error = e35- r.raw = HTTPResponse() # otherwise, tests fail36- r.status_code = 0 # with this status_code, content returns None36+ r.raw = HTTPResponse() # otherwise, tests fail37+ r.status_code = 0 # with this status_code, content returns None38 return r39 return function(method, url, **kwargs)40 return wrappedmodified:requests/sessions.py+1 added-8 removed
16 unmodified lines17 from .hooks import dispatch_hook18 from .utils import header_expand19 from .packages.urllib3.poolmanager import PoolManager20 21+22 def merge_kwargs(local_kwarg, default_kwarg):23 """Merges kwarg dictionaries.24 25 If a local key in the dictionary is set to None, it will be removed.30 unmodified lines56 __attrs__ = [57 'headers', 'cookies', 'auth', 'timeout', 'proxies', 'hooks',58 'params', 'config', 'verify', 'cert', 'prefetch']59 59-60 def __init__(self,61 headers=None,62 cookies=None,63 auth=None,175 unmodified lines239 240 # Return the response.241 return r.response242 243-243 def get(self, url, **kwargs):244 """Sends a GET request. Returns :class:`Response` object.245 246 :param url: URL for the new :class:`Request` object.2 unmodified lines249 250 kwargs.setdefault('allow_redirects', True)251 return self.request('get', url, **kwargs)252 254-253 def options(self, url, **kwargs):254 """Sends a OPTIONS request. Returns :class:`Response` object.255 256 :param url: URL for the new :class:`Request` object.2 unmodified lines259 260 kwargs.setdefault('allow_redirects', True)261 return self.request('options', url, **kwargs)262 265-263 def head(self, url, **kwargs):264 """Sends a HEAD request. Returns :class:`Response` object.265 266 :param url: URL for the new :class:`Request` object.2 unmodified lines269 270 kwargs.setdefault('allow_redirects', False)271 return self.request('head', url, **kwargs)272 276-273 def post(self, url, data=None, **kwargs):274 """Sends a POST request. Returns :class:`Response` object.275 276 :param url: URL for the new :class:`Request` object.2 unmodified lines279 """280 281 return self.request('post', url, data=data, **kwargs)282 287-283 def put(self, url, data=None, **kwargs):284 """Sends a PUT request. Returns :class:`Response` object.285 286 :param url: URL for the new :class:`Request` object.2 unmodified lines289 """290 291 return self.request('put', url, data=data, **kwargs)292 298-293 def patch(self, url, data=None, **kwargs):294 """Sends a PATCH request. Returns :class:`Response` object.295 296 :param url: URL for the new :class:`Request` object.2 unmodified lines299 """300 301 return self.request('patch', url, data=data, **kwargs)302 309-303 def delete(self, url, **kwargs):304 """Sends a DELETE request. Returns :class:`Response` object.305 306 :param url: URL for the new :class:`Request` object.19 unmodified linesmodified:requests/status_codes.py+1 added-1 removed
81 unmodified lines82 for (code, titles) in list(_codes.items()):83 for title in titles:84 setattr(codes, title, code)85 if not title.startswith('\\'):86- setattr(codes, title.upper(), code)86+ setattr(codes, title.upper(), code)modified:requests/structures.py+1 added
45 unmodified lines46 return self[key]47 else:48 return default49 50+51 class LookupDict(dict):52 """Dictionary lookup object."""53 54 def __init__(self, name=None):13 unmodified linesmodified:requests/utils.py+3 added
47 unmodified lines48 # as a fallback (which is generated from pem files in the 'certs' directory):49 '/etc/ssl/ca-bundle.pem',50 ]51 52+53 def get_os_ca_bundle_path():54 """Try to pick an available CA certificate bundle provided by the OS."""55 for path in POSSIBLE_CA_BUNDLE_PATHS:56 if os.path.exists(path):3 unmodified lines60 # if certifi is installed, use its CA bundle;61 # otherwise, try and use the OS bundle62 DEFAULT_CA_BUNDLE_PATH = CERTIFI_BUNDLE_PATH or get_os_ca_bundle_path()63 64+65 def dict_to_sequence(d):66 """Returns an internal sequence dictionary update."""67 68 if hasattr(d, 'items'):377 unmodified lines446 # Then quote only illegal characters (do not quote reserved, unreserved,447 # or '%')448 return quote(unquote_unreserved(uri), safe="!#$%&'()*+,/:;=?@[]~")449 450+451 def get_environ_proxies():452 """Return a dict of environment proxies."""453 454 proxy_keys = [39 unmodified linesmodified:tests/informal/test_leaked_connections.py+1 added
4 unmodified lines5 """6 7 import gc, os, subprocess, requests, sys8 9+10 def main():11 gc.disable()12 13 for x in range(20):14 unmodified linesmodified:tests/test_cookies.py+12 added-9 removed
14 unmodified lines15 # More hacks16 sys.path.append('.')17 from test_requests import httpbin, TestBaseMixin18 19+20 class CookieTests(TestBaseMixin, unittest.TestCase):21 22 def test_cookies_from_response(self):23 """Basic test that we correctly parse received cookies in the Response object."""82 unmodified lines106 107 def test_disabled_cookie_persistence(self):108 """Test that cookies are not persisted when configured accordingly."""109 109- config = {'store_cookies' : False}110+ config = {'store_cookies': False}111 112 # Check the case when no cookie is passed as part of the request and the one in response is ignored112- cookies = requests.get(httpbin('cookies', 'set', 'key', 'value'), config = config).cookies113+ cookies = requests.get(httpbin('cookies', 'set', 'key', 'value'), config=config).cookies114 self.assertTrue(cookies.get("key") is None)115 116 # Test that the cookies passed while making the request still gets used and is available in response object.117 # only the ones received from server is not saved117- cookies_2 = requests.get(httpbin('cookies', 'set', 'key', 'value'), config = config,\118- cookies = {"key_2" : "value_2"}).cookies118+ cookies_2 = requests.get(httpbin('cookies', 'set', 'key', 'value'), config=config,\119+ cookies={"key_2": "value_2"}).cookies120 self.assertEqual(len(cookies_2), 1)121 self.assertEqual(cookies_2.get("key_2"), "value_2")122 123 # Use the session and make sure that the received cookie is not used in subsequent calls124 s = requests.session()124- s.get(httpbin('cookies', 'set', 'key', 'value'), config = config)125+ s.get(httpbin('cookies', 'set', 'key', 'value'), config=config)126 r = s.get(httpbin('cookies'))127 self.assertEqual(json.loads(r.text)['cookies'], {})128 129 def test_jar_utility_functions(self):4 unmodified lines134 self.assertTrue(len(c) >= 1)135 self.assertEqual(len(c), len(r.cookies.keys()))136 self.assertEqual(len(c), len(r.cookies.values()))137 self.assertEqual(len(c), len(r.cookies.items()))137- 138+139 # domain and path utility functions140 domain = r.cookies.list_domains()[0]141 path = r.cookies.list_paths()[0]142 self.assertEqual(dict(r.cookies), r.cookies.get_dict(domain=domain, path=path))8 unmodified lines151 152 # test keys, values, and items153 self.assertEqual(r.cookies.keys(), ['myname'])154 self.assertEqual(r.cookies.values(), ['myvalue'])154- self.assertEqual(r.cookies.items(), [('myname','myvalue')])155- 155+ self.assertEqual(r.cookies.items(), [('myname', 'myvalue')])156+157 # test if we can convert jar to dict158 dictOfCookies = dict(r.cookies)158- self.assertEqual(dictOfCookies, {'myname':'myvalue'})159+ self.assertEqual(dictOfCookies, {'myname': 'myvalue'})160 self.assertEqual(dictOfCookies, r.cookies.get_dict())161 162+163 class LWPCookieJarTest(TestBaseMixin, unittest.TestCase):164 """Check store/load of cookies to FileCookieJar's, specifically LWPCookieJar's."""165 166 COOKIEJAR_CLASS = cookielib.LWPCookieJar88 unmodified lines255 # we should only load the persistent cookie256 self.assertEqual(len(cookiejar_2), 1)257 self.assertCookieHas(list(cookiejar_2)[0], name='Persistent', value='CookiesAreScary')258 259+260 class MozCookieJarTest(LWPCookieJarTest):261 """Same test, but substitute MozillaCookieJar."""262 263 COOKIEJAR_CLASS = cookielib.MozillaCookieJar3 unmodified linesmodified:tests/test_requests_ext.py-8 removed
23 unmodified lines24 25 def test_addition(self):26 assert (1 + 1) == 227 28-28 def test_ssl_hostname_ok(self):29 requests.get('https://github.com', verify=True)30 32-31 def test_ssl_hostname_not_ok(self):32 requests.get('https://kennethreitz.com', verify=False)33 34 self.assertRaises(requests.exceptions.SSLError, requests.get, 'https://kennethreitz.com')35 38-36 def test_ssl_hostname_session_not_ok(self):37 38 s = requests.session()39 40 self.assertRaises(requests.exceptions.SSLError, s.get, 'https://kennethreitz.com')41 42 s.get('https://kennethreitz.com', verify=False)43 47-44 def test_binary_post(self):45 '''We need to be careful how we build the utf-8 string since46 unicode literals are a syntax error in python347 '''6 unmodified lines54 else:55 raise EnvironmentError('Flesh out this test for your environment.')56 requests.post('http://www.google.com/', data=utf8_string)57 62-63-58 def test_unicode_error(self):59 url = 'http://blip.fm/~1abvfu'60 requests.get(url)61 68-62 def test_chunked_head_redirect(self):63 url = "http://t.co/NFrx0zLG"64 r = requests.head(url, allow_redirects=True)65 self.assertEqual(r.status_code, 200)54 unmodified lines120 self.assertTrue('preview' not in json.loads(r2.text)['cookies'])121 122 if __name__ == '__main__':123 unittest.main()131-modified:tests/test_requests_https.py+1 added
7 unmodified lines8 # Path hack.9 sys.path.insert(0, os.path.abspath('..'))10 import requests11 12+13 class HTTPSTest(unittest.TestCase):14 """Smoke test for https functionality."""15 16 smoke_url = "https://github.com"16 unmodified linesmodified:tests/test_requests.py+4 added-5 removed
50 unmodified lines51 # c = envoy.connect('httpbin %s' % (PORT))52 # time.sleep(1)53 _httpbin = True54 55+56 class TestBaseMixin(object):57 58 def assertCookieHas(self, cookie, **kwargs):59 """Assert that a cookie has various specified properties."""1 unmodified line61 cookie_attr = getattr(cookie, attr)62 message = 'Failed comparison for %s: %s != %s' % (attr, cookie_attr, expected_value)63 self.assertEqual(cookie_attr, expected_value, message)64 65+66 class RequestsTestSuite(TestSetup, TestBaseMixin, unittest.TestCase):67 """Requests test cases."""68 69 def test_entry_points(self):280 unmodified lines350 351 post1 = post(url, files={'fname.txt': 'fdata'})352 self.assertEqual(post1.status_code, 200)353 352- post2 = post(url, files={'fname.txt': 'fdata', 'fname2.txt':'more fdata'})354+ post2 = post(url, files={'fname.txt': 'fdata', 'fname2.txt': 'more fdata'})355 self.assertEqual(post2.status_code, 200)356 355- post3 = post(url, files={'fname.txt': 'fdata', 'fname2.txt':open(__file__,'rb')})357+ post3 = post(url, files={'fname.txt': 'fdata', 'fname2.txt': open(__file__, 'rb')})358 self.assertEqual(post3.status_code, 200)359 360 post4 = post(url, files={'fname.txt': 'fdata'})361 self.assertEqual(post4.status_code, 200)16 unmodified lines378 self.assertTrue(rbody.get('files', None))379 self.assertTrue(rbody['files'].get('fname.txt'), None)380 self.assertEqual(rbody['files']['fname.txt'], 'fdata to verify')381 380-382 def test_nonzero_evaluation(self):383 384 for service in SERVICES:385 438 unmodified lines824 config = {'safe_mode': True}825 r = get('http://localhost:1/nope', allow_redirects=False, config=config)826 assert r.content == None827 827-828 # def test_invalid_content(self):829 # # WARNING: if you're using a terrible DNS provider (comcast),830 # # this will fail.831 # try:107 unmodified lines939 s = requests.session()940 s.config['danger_mode'] = True941 s.get(httpbin('redirect', '4'))942 943-943 def test_empty_response(self):944 r = requests.get(httpbin('status', '404'))945 r.text946 125 unmodified lines