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
Provenance
- Commit
4285bac- Tree
3c21ce1- Author
Kenneth Reitz <me@kennethreitz.org>- Committer
GitHub <noreply@github.com>- Parent 1
75d72ca- Parent 2
2d4a89f
12 files changed+39 added−29 removed
modified:requests/auth.py+3 added
41 unmodified lines42 43 44 class HTTPBasicAuth(AuthBase):45 """Attaches HTTP Basic Authentication to the given Request object."""46+47 def __init__(self, username, password):48 self.username = username49 self.password = password50 12 unmodified lines63 64 65 class HTTPProxyAuth(HTTPBasicAuth):66 """Attaches HTTP Proxy Authentication to a given Request object."""67+68 def __call__(self, r):69 r.headers['Proxy-Authorization'] = _basic_auth_str(self.username, self.password)70 return r71 72 73 class HTTPDigestAuth(AuthBase):74 """Attaches HTTP Digest Authentication to the given Request object."""75+76 def __init__(self, username, password):77 self.username = username78 self.password = password79 # Keep state in per-thread local storage166 unmodified linesmodified:requests/cookies.py+1 added
176 unmodified lines177 Unlike a regular CookieJar, this class is pickleable.178 179 .. warning:: dictionary operations that are normally O(1) may be O(n).180 """181+182 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 linesmodified:requests/hooks.py+1 added
12 unmodified lines13 14 """15 HOOKS = ['response']16 17+18 def default_hooks():19 return dict((event, []) for event in HOOKS)20 21 # TODO: response is the only one14 unmodified linesmodified:requests/models.py+7 added-6 removed
25 unmodified lines26 ContentDecodingError, ConnectionError, StreamConsumedError)27 from .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)32 from .compat import (33 cookielib, urlunparse, urlsplit, urlencode, str, bytes, StringIO,34 is_py2, chardet, builtin_str, basestring)2 unmodified lines37 38 #: The set of HTTP status codes that indicate an automatically39 #: processable redirect.40 REDIRECT_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 )47 48 DEFAULT_REDIRECT_LIMIT = 3049 CONTENT_CHUNK_SIZE = 10 * 1024158 unmodified lines208 >>> req.prepare()209 <PreparedRequest [GET]>210 211 """212+213 def __init__(self, method=None, url=None, headers=None, files=None,214 data=None, params=None, auth=None, cookies=None, hooks=None, json=None):215 216 # Default empty dicts for dict params.660 unmodified linesmodified:requests/sessions.py+1 added-2 removed
193 unmodified lines194 url = prepared_request.url195 196 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)201 202 if (original_parsed.hostname != redirect_parsed.hostname):172 unmodified lines375 # Merge with session cookies376 merged_cookies = merge_cookies(377 merge_cookies(RequestsCookieJar(), self.cookies), cookies)378 379-379 # 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 linesmodified:requests/status_codes.py+1 added-1 removed
29 unmodified lines30 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.035 36 # Client Error.37 400: ('bad_request', 'bad'),38 401: ('unauthorized',),53 unmodified linesmodified:requests/structures.py+2 added
39 unmodified lines40 operations are given keys that have equal ``.lower()``s, the41 behavior is undefined.42 43 """44+45 def __init__(self, data=None, **kwargs):46 self._store = OrderedDict()47 if data is None:48 data = {}38 unmodified lines87 88 def __repr__(self):89 return str(dict(self.items()))90 91+92 class LookupDict(dict):93 """Dictionary lookup object."""94 95 def __init__(self, name=None):13 unmodified linesmodified:requests/utils.py+4 added-2 removed
382 unmodified lines383 384 def 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_length341 unmodified lines733 out = string.decode(encoding)734 735 return out736 737+738 # 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 lines755 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)))761 762+763 def urldefragauth(url):764 """765 Given a url remove the fragment and the authentication part766 """9 unmodified linesmodified:tests/test_lowlevel.py+1 added-1 removed
15 unmodified lines16 17 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 block21 22 assert r.status_code == 20023 assert r.request.headers['Transfer-Encoding'] == 'chunked'24 32 unmodified linesmodified:tests/test_requests.py+4 added-6 removed
562 unmodified lines563 post1 = requests.post(url, data={'some': 'data'})564 assert post1.status_code == 200565 566 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 == 200569 570 post4 = requests.post(url, data='[{"some": "json"}]')571 assert post4.status_code == 200366 unmodified lines938 939 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.0944 945 def test_response_is_iterable(self):946 r = requests.Response()40 unmodified lines987 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 here992 993 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 lines1149 """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']}1155 1156 # Test for int1157 with pytest.raises(InvalidHeader):628 unmodified linesmodified:tests/test_testserver.py+13 added-11 removed
4 unmodified lines5 import pytest6 import requests7 from tests.testserver.server import Server8 9+10 class TestTestServer:11+12 def test_basic(self):13 """messages are sent and received properly"""14 question = b"sucess?"15 answer = b"yeah, success"16+17 def handler(sock):18 text = sock.recv(1000)16- assert text == question 19+ assert text == question20 sock.sendall(answer)18- 21+22 with Server(handler) as (host, port):23 sock = socket.socket()24 sock.connect((host, port))25 sock.sendall(question)15 unmodified lines41 42 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 line51 r = requests.get('http://{0}:{1}'.format(host, port))52 53 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'56+57 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 lines71 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 block76 77 def test_multiple_requests(self):78 """multiple requests can be served"""79 requests_to_handle = 577- 80+81 server = Server.basic_response_server(requests_to_handle=requests_to_handle)82 83 with server as (host, port):84 server_url = 'http://{0}:{1}'.format(host, port)13 unmodified lines98 99 with server as address:100 sock1 = socket.socket()101 sock2 = socket.socket()99- 102+103 sock1.connect(address)104 sock1.sendall(first_request)105 sock1.close()106 16 unmodified lines123 sock.close()124 125 assert server.handler_results[0] == b''126 124-127 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'131 132 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- 138+139 assert server.handler_results[0] == data140 141 def test_server_finishes_on_error(self):142 """the server thread exits even if an exception exits the context manager"""20 unmodified linesmodified:tests/test_utils.py+1 added
387 unmodified lines388 assert len(list(iter_slices(value, length))) == 1389 else:390 assert len(list(iter_slices(value, 1))) == length391 392+393 @pytest.mark.parametrize(394 'value, expected', (395 (396 '<http:/.../front.jpeg>; rel=front; type="image/jpeg"',72 unmodified lines