Skip to content
Myr

Merge pull request #3428 from nateprewitt/pep8_fixes

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

adding in pep8 fixes

authored by Kenneth Reitz · committed by GitHub · parents 75d72ca, 2d4a89f · Browse files · 12 files+39 added−29 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+39 added−29 removed

  • tests:+19 added−18 removed
  • other:+20 added−11 removed

12 files+39 added−29 removed

modified:requests/auth.py+3 added
41 unmodified lines
424344class HTTPBasicAuth(AuthBase):45 """Attaches HTTP Basic Authentication to the given Request object."""4647 def __init__(self, username, password):48 self.username = username49 self.password = password50
12 unmodified lines
636465class HTTPProxyAuth(HTTPBasicAuth):66 """Attaches HTTP Proxy Authentication to a given Request object."""6768 def __call__(self, r):69 r.headers['Proxy-Authorization'] = _basic_auth_str(self.username, self.password)70 return r717273class HTTPDigestAuth(AuthBase):74 """Attaches HTTP Digest Authentication to the given Request object."""7576 def __init__(self, username, password):77 self.username = username78 self.password = password79 # Keep state in per-thread local storage
166 unmodified lines
modified:requests/cookies.py+1 added
176 unmodified lines
177 Unlike a regular CookieJar, this class is pickleable.178179 .. warning:: dictionary operations that are normally O(1) may be O(n).180 """181182 def get(self, name, default=None, domain=None, path=None):183 """Dict-like get() that also supports optional domain and path args in184 order to resolve naming collisions from using one cookie jar over185 multiple domains.
309 unmodified lines
modified:requests/hooks.py+1 added
12 unmodified lines
1314"""15HOOKS = ['response']161718def default_hooks():19 return dict((event, []) for event in HOOKS)2021# TODO: response is the only one
14 unmodified lines
modified:requests/models.py+7 added-6 removed
25 unmodified lines
26 ContentDecodingError, ConnectionError, StreamConsumedError)27from .utils import (28 guess_filename, get_auth_from_url, requote_uri,29 stream_decode_response_unicode, to_key_val_list, parse_header_links,30 iter_slices, guess_json_utf, super_len, to_native_string, 30 iter_slices, guess_json_utf, super_len, to_native_string,31 check_header_validity)32from .compat import (33 cookielib, urlunparse, urlsplit, urlencode, str, bytes, StringIO,34 is_py2, chardet, builtin_str, basestring)
2 unmodified lines
3738#: The set of HTTP status codes that indicate an automatically39#: processable redirect.40REDIRECT_STATI = (41 codes.moved, # 30142 codes.found, # 30243 codes.other, # 30344 codes.temporary_redirect, # 30745 codes.permanent_redirect, # 30841 codes.moved, # 30142 codes.found, # 30243 codes.other, # 30344 codes.temporary_redirect, # 30745 codes.permanent_redirect, # 30846)4748DEFAULT_REDIRECT_LIMIT = 3049CONTENT_CHUNK_SIZE = 10 * 1024
158 unmodified lines
208 >>> req.prepare()209 <PreparedRequest [GET]>210211 """212213 def __init__(self, method=None, url=None, headers=None, files=None,214 data=None, params=None, auth=None, cookies=None, hooks=None, json=None):215216 # Default empty dicts for dict params.
660 unmodified lines
modified:requests/sessions.py+1 added-2 removed
193 unmodified lines
194 url = prepared_request.url195196 if 'Authorization' in headers:197 # If we get redirected to a new host, we should strip out any198 # authentication headers.198 # authentication headers.199 original_parsed = urlparse(response.request.url)200 redirect_parsed = urlparse(url)201202 if (original_parsed.hostname != redirect_parsed.hostname):
172 unmodified lines
375 # Merge with session cookies376 merged_cookies = merge_cookies(377 merge_cookies(RequestsCookieJar(), self.cookies), cookies)378379379 # Set environment's basic authentication if not explicitly set.380 auth = request.auth381 if self.trust_env and not auth and not self.auth:382 auth = get_netrc_auth(request.url)
308 unmodified lines
modified:requests/status_codes.py+1 added-1 removed
29 unmodified lines
30 305: ('use_proxy',),31 306: ('switch_proxy',),32 307: ('temporary_redirect', 'temporary_moved', 'temporary'),33 308: ('permanent_redirect',34 'resume_incomplete', 'resume',), # These 2 to be removed in 3.034 'resume_incomplete', 'resume',), # These 2 to be removed in 3.03536 # Client Error.37 400: ('bad_request', 'bad'),38 401: ('unauthorized',),
53 unmodified lines
modified:requests/structures.py+2 added
39 unmodified lines
40 operations are given keys that have equal ``.lower()``s, the41 behavior is undefined.4243 """4445 def __init__(self, data=None, **kwargs):46 self._store = OrderedDict()47 if data is None:48 data = {}
38 unmodified lines
8788 def __repr__(self):89 return str(dict(self.items()))909192class LookupDict(dict):93 """Dictionary lookup object."""9495 def __init__(self, name=None):
13 unmodified lines
modified:requests/utils.py+4 added-2 removed
382 unmodified lines
383384def iter_slices(string, slice_length):385 """Iterate over slices of a string."""386 pos = 0387 if slice_length is None or slice_length <= 0: 387 if slice_length is None or slice_length <= 0:388 slice_length = len(string)389 while pos < len(string):390 yield string[pos:pos + slice_length]391 pos += slice_length
341 unmodified lines
733 out = string.decode(encoding)734735 return out736737738# Moved outside of function to avoid recompile every call739_CLEAN_HEADER_REGEX_BYTE = re.compile(b'^\\S[^\\r\\n]*$|^$')740_CLEAN_HEADER_REGEX_STR = re.compile(r'^\S[^\r\n]*$|^$')741
13 unmodified lines
755 try:756 if not pat.match(value):757 raise InvalidHeader("Invalid return character or leading space in header: %s" % name)758 except TypeError:758 raise InvalidHeader("Header value %s must be of type str or bytes, " 759 raise InvalidHeader("Header value %s must be of type str or bytes, "760 "not %s" % (value, type(value)))761762763def urldefragauth(url):764 """765 Given a url remove the fragment and the authentication part766 """
9 unmodified lines
modified:tests/test_lowlevel.py+1 added-1 removed
15 unmodified lines
1617 with server as (host, port):18 url = 'http://{0}:{1}/'.format(host, port)19 r = requests.post(url, data=data, stream=True)20 close_server.set() # release server block20 close_server.set() # release server block2122 assert r.status_code == 20023 assert r.request.headers['Transfer-Encoding'] == 'chunked'24
32 unmodified lines
modified:tests/test_requests.py+4 added-6 removed
562 unmodified lines
563 post1 = requests.post(url, data={'some': 'data'})564 assert post1.status_code == 200565566 with open('requirements.txt') as f:567 post2 = requests.post(url,568 data={'some': 'data'}, files={'some': f})567 post2 = requests.post(url, data={'some': 'data'}, files={'some': f})568 assert post2.status_code == 200569570 post4 = requests.post(url, data='[{"some": "json"}]')571 assert post4.status_code == 200
366 unmodified lines
938939 def test_time_elapsed_blank(self, httpbin):940 r = requests.get(httpbin('get'))941 td = r.elapsed943 total_seconds = ((td.microseconds + (td.seconds + td.days * 24 * 3600)944 * 10**6) / 10**6)942 total_seconds = ((td.microseconds + (td.seconds + td.days * 24 * 3600) * 10**6) / 10**6)943 assert total_seconds > 0.0944945 def test_response_is_iterable(self):946 r = requests.Response()
40 unmodified lines
987 r.url = u'unicode URL'988 r.reason = u'Komponenttia ei löydy'.encode('utf-8')989 r.status_code = 404990 r.encoding = None993 assert not r.ok # old behaviour - crashes here991 assert not r.ok # old behaviour - crashes here992993 def test_response_chunk_size_type(self):994 """Ensure that chunk_size is passed as None or an integer, otherwise995 raise a TypeError.
153 unmodified lines
1149 """Ensure the header value is of type string or bytes as1150 per discussion in GH issue #33861151 """1152 headers_int = {'foo': 3}1155 headers_dict = {'bar': {'foo':'bar'}}1153 headers_dict = {'bar': {'foo': 'bar'}}1154 headers_list = {'baz': ['foo', 'bar']}11551156 # Test for int1157 with pytest.raises(InvalidHeader):
628 unmodified lines
modified:tests/test_testserver.py+13 added-11 removed
4 unmodified lines
5import pytest6import requests7from tests.testserver.server import Server8910class TestTestServer:1112 def test_basic(self):13 """messages are sent and received properly"""14 question = b"sucess?"15 answer = b"yeah, success"1617 def handler(sock):18 text = sock.recv(1000)16 assert text == question 19 assert text == question20 sock.sendall(answer)18 2122 with Server(handler) as (host, port):23 sock = socket.socket()24 sock.connect((host, port))25 sock.sendall(question)
15 unmodified lines
4142 def test_text_response(self):43 """the text_response_server sends the given text"""44 server = Server.text_response_server(42 "HTTP/1.1 200 OK\r\n" + 45 "HTTP/1.1 200 OK\r\n" +46 "Content-Length: 6\r\n" +47 "\r\nroflol"48 )49
1 unmodified line
51 r = requests.get('http://{0}:{1}'.format(host, port))5253 assert r.status_code == 20054 assert r.text == u'roflol'52 assert r.headers['Content-Length'] == '6' 53 55 assert r.headers['Content-Length'] == '6'5657 def test_basic_response(self):58 """the basic response server returns an empty http response"""59 with Server.basic_response_server() as (host, port):60 r = requests.get('http://{0}:{1}'.format(host, port))
10 unmodified lines
71 sock.connect((host, port))72 sock.sendall(b'send something')73 time.sleep(2.5)74 sock.sendall(b'still alive')72 block_server.set() # release server block75 block_server.set() # release server block7677 def test_multiple_requests(self):78 """multiple requests can be served"""79 requests_to_handle = 577 8081 server = Server.basic_response_server(requests_to_handle=requests_to_handle)8283 with server as (host, port):84 server_url = 'http://{0}:{1}'.format(host, port)
13 unmodified lines
9899 with server as address:100 sock1 = socket.socket()101 sock2 = socket.socket()99 102103 sock1.connect(address)104 sock1.sendall(first_request)105 sock1.close()106
16 unmodified lines
123 sock.close()124125 assert server.handler_results[0] == b''126124127 def test_request_recovery_with_bigger_timeout(self):128 """a biggest timeout can be specified"""129 server = Server.basic_response_server(request_timeout=3)130 data = b'bananadine'131132 with server as address:131 sock = socket.socket() 133 sock = socket.socket()134 sock.connect(address)135 time.sleep(1.5)136 sock.sendall(data)137 sock.close()136 138139 assert server.handler_results[0] == data140141 def test_server_finishes_on_error(self):142 """the server thread exits even if an exception exits the context manager"""
20 unmodified lines
modified:tests/test_utils.py+1 added
387 unmodified lines
388 assert len(list(iter_slices(value, length))) == 1389 else:390 assert len(list(iter_slices(value, 1))) == length391392393@pytest.mark.parametrize(394 'value, expected', (395 (396 '<http:/.../front.jpeg>; rel=front; type="image/jpeg"',
72 unmodified lines