Skip to content
Myr

Merge pull request #786 from Locker537/lint_fix

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Lint fixes following PEP8.

authored by Kenneth Reitz · committed by Kenneth Reitz · parents bbf1946, 42d0a21 · 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

17 files+67 added−47 removed

modified:requests/api.py+2 added
12 unmodified lines
1314from . import sessions15from .safe_mode import catch_exceptions_if_in_safe_mode161718@catch_exceptions_if_in_safe_mode19def request(method, url, **kwargs):20 """Constructs and sends a :class:`Request <Request>`.21 Returns :class:`Response <Response>` object.
30 unmodified lines
52 finally:53 if adhoc_session:54 session.close()555657def get(url, **kwargs):58 """Sends a GET request. Returns :class:`Response` object.5960 :param url: URL for the new :class:`Request` object.
70 unmodified lines
modified:requests/auth.py+3 added
32 unmodified lines
33log = logging.getLogger(__name__)3435CONTENT_TYPE_FORM_URLENCODED = 'application/x-www-form-urlencoded'363738def _basic_auth_str(username, password):39 """Returns a Basic Auth string."""4041 return 'Basic ' + b64encode(('%s:%s' % (username, password)).encode('latin1')).strip().decode('latin1')
197 unmodified lines
239 def __call__(self, r):240 r.register_hook('response', self.handle_401)241 return r242243244def _negotiate_value(r):245 """Extracts the gssapi authentication token from the appropriate header"""246247 authreq = r.headers.get('www-authenticate', None)
5 unmodified lines
253 return mo.group(1)254255 return None256257258class 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 lines
modified:requests/compat.py-1 removed
110 unmodified lines
111 str = str112 bytes = bytes113 basestring = (str,bytes)114 numeric_types = (int, float)115
modified:requests/cookies.py+20 added-10 removed
12 unmodified lines
13 threading14except ImportError:15 import dummy_threading as threading161718class MockRequest(object):19 """Wraps a `requests.Request` to mimic a `urllib2.Request`.2021 The code in `cookielib.CookieJar` expects this interface in order to correctly
44 unmodified lines
6667 def get_new_headers(self):68 return self._new_headers697071class MockResponse(object):72 """Wraps a `httplib.HTTPMessage` to mimic a `urllib.addinfourl`.7374 ...what? Basically, expose the parsed HTTP headers from the server response
12 unmodified lines
8788 def getheaders(self, name):89 self._headers.getheaders(name)909192def extract_cookies_to_jar(jar, request, response):93 """Extract the cookies from the response into a CookieJar.9495 :param jar: cookielib.CookieJar (not necessarily a RequestsCookieJar)
5 unmodified lines
101 # 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)104105106def 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')111112113def remove_cookie_by_name(cookiejar, name, domain=None, path=None):114 """Unsets a cookie by name, by default over all domains and paths.115116 Wraps CookieJar.clear(), is O(n).
7 unmodified lines
124125 for domain, path, name in clearables:126 cookiejar.clear(domain, path, name)127128129class 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."""132133134class RequestsCookieJar(cookielib.CookieJar, collections.MutableMapping):135 """Compatibility class; is a cookielib.CookieJar, but exposes a dict interface.136137 This is the CookieJar we create by default for requests and sessions that
49 unmodified lines
187 values = []188 for cookie in iter(self):189 values.append(cookie.value)190 return values184 191192 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 lines
221 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 jar226227 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 lines
250 """Deletes a cookie given a name. Wraps cookielib.CookieJar's remove_cookie_by_name()."""251 remove_cookie_by_name(self, name)252253 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 lines
263264 raise KeyError('name=%r, domain=%r, path=%r' % (name, domain, path))265266 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 conflict279280 if toReturn:281 return toReturn282 raise KeyError('name=%r, domain=%r, path=%r' % (name, domain, path))
14 unmodified lines
297 def copy(self):298 """This is not implemented. Calling this will throw an exception."""299 raise NotImplementedError300301302def create_cookie(name, value, **kwargs):303 """Make a cookie from underspecified parameters.304305 By default, the pair of `name` and `value` will be set for the domain ''
27 unmodified lines
333 result['path_specified'] = bool(result['path'])334335 return cookielib.Cookie(**result)336337338def 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 lines
357 rfc2109=False,358 )359 return c360361362def cookiejar_from_dict(cookie_dict, cookiejar=None):363 """Returns a CookieJar from a key/value dictionary.364365 :param cookie_dict: Dict of key/values to insert into CookieJar.
8 unmodified lines
modified:requests/exceptions.py+10 added
6 unmodified lines
7This module contains the set of Requests' exceptions.89"""101112class RequestException(RuntimeError):13 """There was an ambiguous exception that occurred while handling your14 request."""151617class HTTPError(RequestException):18 """An HTTP error occurred."""19 response = None202122class ConnectionError(RequestException):23 """A Connection error occurred."""242526class SSLError(ConnectionError):27 """An SSL error occurred."""282930class Timeout(RequestException):31 """The request timed out."""323334class URLRequired(RequestException):35 """A valid URL is required to make a request."""363738class TooManyRedirects(RequestException):39 """Too many redirects."""404142class MissingSchema(RequestException, ValueError):43 """The URL schema (e.g. http or https) is missing."""444546class InvalidSchema(RequestException, ValueError):47 """See defaults.py for valid schemas."""484950class InvalidURL(RequestException, ValueError):51 """ The URL provided was somehow invalid. """
modified:requests/hooks.py+1 added
28 unmodified lines
293031HOOKS = ('args', 'pre_request', 'pre_send', 'post_request', 'response')323334def dispatch_hook(key, hooks, hook_data):35 """Dispatches a hook dictionary on a given piece of data."""3637 hooks = hooks or dict()
17 unmodified lines
modified:requests/models.py+2 added-1 removed
37 unmodified lines
3839REDIRECT_STATI = (codes.moved, codes.found, codes.other, codes.temporary_moved)40CONTENT_CHUNK_SIZE = 10 * 1024414243class 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 lines
553 # Update self to reflect the auth changes.554 self.__dict__.update(r.__dict__)555556 _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)559560 if proxy and not any(map(_p.netloc.endswith, no_proxy)):561 conn = poolmanager.proxy_from_url(proxy)
325 unmodified lines
modified:requests/safe_mode.py+5 added-4 removed
14 unmodified lines
15from .packages.urllib3.response import HTTPResponse16from .exceptions import RequestException, ConnectionError, HTTPError17import socket181920def 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 2526 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 wrapped
modified:requests/sessions.py+1 added-8 removed
16 unmodified lines
17from .hooks import dispatch_hook18from .utils import header_expand19from .packages.urllib3.poolmanager import PoolManager202122def merge_kwargs(local_kwarg, default_kwarg):23 """Merges kwarg dictionaries.2425 If a local key in the dictionary is set to None, it will be removed.
30 unmodified lines
56 __attrs__ = [57 'headers', 'cookies', 'auth', 'timeout', 'proxies', 'hooks',58 'params', 'config', 'verify', 'cert', 'prefetch']595960 def __init__(self,61 headers=None,62 cookies=None,63 auth=None,
175 unmodified lines
239240 # Return the response.241 return r.response242243243 def get(self, url, **kwargs):244 """Sends a GET request. Returns :class:`Response` object.245246 :param url: URL for the new :class:`Request` object.
2 unmodified lines
249250 kwargs.setdefault('allow_redirects', True)251 return self.request('get', url, **kwargs)252254253 def options(self, url, **kwargs):254 """Sends a OPTIONS request. Returns :class:`Response` object.255256 :param url: URL for the new :class:`Request` object.
2 unmodified lines
259260 kwargs.setdefault('allow_redirects', True)261 return self.request('options', url, **kwargs)262265263 def head(self, url, **kwargs):264 """Sends a HEAD request. Returns :class:`Response` object.265266 :param url: URL for the new :class:`Request` object.
2 unmodified lines
269270 kwargs.setdefault('allow_redirects', False)271 return self.request('head', url, **kwargs)272276273 def post(self, url, data=None, **kwargs):274 """Sends a POST request. Returns :class:`Response` object.275276 :param url: URL for the new :class:`Request` object.
2 unmodified lines
279 """280281 return self.request('post', url, data=data, **kwargs)282287283 def put(self, url, data=None, **kwargs):284 """Sends a PUT request. Returns :class:`Response` object.285286 :param url: URL for the new :class:`Request` object.
2 unmodified lines
289 """290291 return self.request('put', url, data=data, **kwargs)292298293 def patch(self, url, data=None, **kwargs):294 """Sends a PATCH request. Returns :class:`Response` object.295296 :param url: URL for the new :class:`Request` object.
2 unmodified lines
299 """300301 return self.request('patch', url, data=data, **kwargs)302309303 def delete(self, url, **kwargs):304 """Sends a DELETE request. Returns :class:`Response` object.305306 :param url: URL for the new :class:`Request` object.
19 unmodified lines
modified:requests/status_codes.py+1 added-1 removed
81 unmodified lines
82for (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 lines
46 return self[key]47 else:48 return default495051class LookupDict(dict):52 """Dictionary lookup object."""5354 def __init__(self, name=None):
13 unmodified lines
modified:requests/utils.py+3 added
47 unmodified lines
48 # as a fallback (which is generated from pem files in the 'certs' directory):49 '/etc/ssl/ca-bundle.pem',50]515253def 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 lines
60# if certifi is installed, use its CA bundle;61# otherwise, try and use the OS bundle62DEFAULT_CA_BUNDLE_PATH = CERTIFI_BUNDLE_PATH or get_os_ca_bundle_path()636465def dict_to_sequence(d):66 """Returns an internal sequence dictionary update."""6768 if hasattr(d, 'items'):
377 unmodified lines
446 # Then quote only illegal characters (do not quote reserved, unreserved,447 # or '%')448 return quote(unquote_unreserved(uri), safe="!#$%&'()*+,/:;=?@[]~")449450451def get_environ_proxies():452 """Return a dict of environment proxies."""453454 proxy_keys = [
39 unmodified lines
modified:tests/informal/test_leaked_connections.py+1 added
4 unmodified lines
5"""67import gc, os, subprocess, requests, sys8910def main():11 gc.disable()1213 for x in range(20):
14 unmodified lines
modified:tests/test_cookies.py+12 added-9 removed
14 unmodified lines
15# More hacks16sys.path.append('.')17from test_requests import httpbin, TestBaseMixin181920class CookieTests(TestBaseMixin, unittest.TestCase):2122 def test_cookies_from_response(self):23 """Basic test that we correctly parse received cookies in the Response object."""
82 unmodified lines
106107 def test_disabled_cookie_persistence(self):108 """Test that cookies are not persisted when configured accordingly."""109109 config = {'store_cookies' : False}110 config = {'store_cookies': False}111112 # 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)115116 # 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")122123 # 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'], {})128129 def test_jar_utility_functions(self):
4 unmodified lines
134 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 138139 # 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 lines
151152 # 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')])156157 # 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())161162163class LWPCookieJarTest(TestBaseMixin, unittest.TestCase):164 """Check store/load of cookies to FileCookieJar's, specifically LWPCookieJar's."""165166 COOKIEJAR_CLASS = cookielib.LWPCookieJar
88 unmodified lines
255 # we should only load the persistent cookie256 self.assertEqual(len(cookiejar_2), 1)257 self.assertCookieHas(list(cookiejar_2)[0], name='Persistent', value='CookiesAreScary')258259260class MozCookieJarTest(LWPCookieJarTest):261 """Same test, but substitute MozillaCookieJar."""262263 COOKIEJAR_CLASS = cookielib.MozillaCookieJar
3 unmodified lines
modified:tests/test_requests_ext.py-8 removed
23 unmodified lines
2425 def test_addition(self):26 assert (1 + 1) == 2272828 def test_ssl_hostname_ok(self):29 requests.get('https://github.com', verify=True)303231 def test_ssl_hostname_not_ok(self):32 requests.get('https://kennethreitz.com', verify=False)3334 self.assertRaises(requests.exceptions.SSLError, requests.get, 'https://kennethreitz.com')353836 def test_ssl_hostname_session_not_ok(self):3738 s = requests.session()3940 self.assertRaises(requests.exceptions.SSLError, s.get, 'https://kennethreitz.com')4142 s.get('https://kennethreitz.com', verify=False)434744 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 lines
54 else:55 raise EnvironmentError('Flesh out this test for your environment.')56 requests.post('http://www.google.com/', data=utf8_string)57626358 def test_unicode_error(self):59 url = 'http://blip.fm/~1abvfu'60 requests.get(url)616862 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 lines
120 self.assertTrue('preview' not in json.loads(r2.text)['cookies'])121122if __name__ == '__main__':123 unittest.main()131
modified:tests/test_requests_https.py+1 added
7 unmodified lines
8# Path hack.9sys.path.insert(0, os.path.abspath('..'))10import requests111213class HTTPSTest(unittest.TestCase):14 """Smoke test for https functionality."""1516 smoke_url = "https://github.com"
16 unmodified lines
modified:tests/test_requests.py+4 added-5 removed
50 unmodified lines
51 # c = envoy.connect('httpbin %s' % (PORT))52 # time.sleep(1)53 _httpbin = True545556class TestBaseMixin(object):5758 def assertCookieHas(self, cookie, **kwargs):59 """Assert that a cookie has various specified properties."""
1 unmodified line
61 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)646566class RequestsTestSuite(TestSetup, TestBaseMixin, unittest.TestCase):67 """Requests test cases."""6869 def test_entry_points(self):
280 unmodified lines
350351 post1 = post(url, files={'fname.txt': 'fdata'})352 self.assertEqual(post1.status_code, 200)353352 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)356355 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)359360 post4 = post(url, files={'fname.txt': 'fdata'})361 self.assertEqual(post4.status_code, 200)
16 unmodified lines
378 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')381380382 def test_nonzero_evaluation(self):383384 for service in SERVICES:385
438 unmodified lines
824 config = {'safe_mode': True}825 r = get('http://localhost:1/nope', allow_redirects=False, config=config)826 assert r.content == None827827828 # def test_invalid_content(self):829 # # WARNING: if you're using a terrible DNS provider (comcast),830 # # this will fail.831 # try:
107 unmodified lines
939 s = requests.session()940 s.config['danger_mode'] = True941 s.get(httpbin('redirect', '4'))942943943 def test_empty_response(self):944 r = requests.get(httpbin('status', '404'))945 r.text946
125 unmodified lines