Merge remote-tracking branch 'origin/master'
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 795f185, ba3dab5 · Browse files · 7 files·+158 added−34 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
7 files+158 added−34 removed
- other:+158 added−34 removed
Provenance
- Commit
57c4684- Tree
351b4df- Author
Kenneth Reitz <me@kennethreitz.com>- Committer
Kenneth Reitz <me@kennethreitz.com>- Parent 1
795f185- Parent 2
ba3dab5
7 files changed+158 added−34 removed
modified:requests/adapters.py+30 added-17 removed
328 unmodified lines329 if hasattr(conn, 'proxy_pool'):330 conn = conn.proxy_pool331 332 low_conn = conn._get_conn(timeout=timeout)333- low_conn.putrequest(request.method, url, skip_accept_encoding=True)333 335- for header, value in request.headers.items():336- low_conn.putheader(header, value)334+ try:335+ low_conn.putrequest(request.method,336+ url,337+ skip_accept_encoding=True)338 338- low_conn.endheaders()339+ for header, value in request.headers.items():340+ low_conn.putheader(header, value)341 340- for i in request.body:341- low_conn.send(hex(len(i))[2:].encode('utf-8'))342- low_conn.send(b'\r\n')343- low_conn.send(i)344- low_conn.send(b'\r\n')345- low_conn.send(b'0\r\n\r\n')342+ low_conn.endheaders()343 347- r = low_conn.getresponse()348- resp = HTTPResponse.from_httplib(r,349- pool=conn,350- connection=low_conn,351- preload_content=False,352- decode_content=False353- )344+ for i in request.body:345+ low_conn.send(hex(len(i))[2:].encode('utf-8'))346+ low_conn.send(b'\r\n')347+ low_conn.send(i)348+ low_conn.send(b'\r\n')349+ low_conn.send(b'0\r\n\r\n')350 351+ r = low_conn.getresponse()352+ resp = HTTPResponse.from_httplib(353+ r,354+ pool=conn,355+ connection=low_conn,356+ preload_content=False,357+ decode_content=False358+ )359+ except:360+ # If we hit any problems here, clean up the connection.361+ # Then, reraise so that we can handle the actual exception.362+ low_conn.close()363+ raise364+ else:365+ # All is well, return the connection to the pool.366+ conn._put_conn(low_conn)367+368 except socket.error as sockerr:369 raise ConnectionError(sockerr)370 371 except MaxRetryError as e:19 unmodified linesmodified:requests/auth.py+3 added-1 removed
14 unmodified lines15 16 from base64 import b64encode17 18 from .compat import urlparse, str19+from .cookies import extract_cookies_to_jar20 from .utils import parse_dict_header21 22 log = logging.getLogger(__name__)23 145 unmodified lines169 # to allow our new request to reuse the same one.170 r.content171 r.raw.release_conn()172 prep = r.request.copy()173+ extract_cookies_to_jar(prep._cookies, r.request, r.raw)172- prep.prepare_cookies(r.cookies)174+ prep.prepare_cookies(prep._cookies)175 176 prep.headers['Authorization'] = self.build_digest_header(177 prep.method, prep.url)178 _r = r.connection.send(prep, **kwargs)18 unmodified linesmodified:requests/models.py+9 added-6 removed
268 unmodified lines269 #: HTTP URL to send the request to.270 self.url = None271 #: dictionary of HTTP headers.272 self.headers = None273+ # The `CookieJar` used to create the Cookie header will be stored here274+ # after prepare_cookies is called275+ self._cookies = None276 #: request body to send to the server.277 self.body = None278 #: dictionary of callback hooks, for internal usage.279 self.hooks = default_hooks()21 unmodified lines301 p = PreparedRequest()302 p.method = self.method303 p.url = self.url304 p.headers = self.headers.copy()305+ p._cookies = self._cookies.copy()306 p.body = self.body307 p.hooks = self.hooks308 return p309 167 unmodified lines477 def prepare_cookies(self, cookies):478 """Prepares the given HTTP cookie data."""479 480 if isinstance(cookies, cookielib.CookieJar):477- cookies = cookies481+ self._cookies = cookies482 else:479- cookies = cookiejar_from_dict(cookies)483+ self._cookies = cookiejar_from_dict(cookies)484 481- if 'cookie' not in self.headers:482- cookie_header = get_cookie_header(cookies, self)483- if cookie_header is not None:484- self.headers['Cookie'] = cookie_header485+ cookie_header = get_cookie_header(self._cookies, self)486+ if cookie_header is not None:487+ self.headers['Cookie'] = cookie_header488 489 def prepare_hooks(self, hooks):490 """Prepares the given hooks."""491 for event in hooks:282 unmodified linesmodified:requests/sessions.py+3 added-4 removed
151 unmodified lines152 del headers['Cookie']153 except KeyError:154 pass155 156+ extract_cookies_to_jar(prepared_request._cookies,157+ prepared_request, resp.raw)156- prepared_request.prepare_cookies(self.cookies)158+ prepared_request.prepare_cookies(prepared_request._cookies)159 160 resp = self.send(161 prepared_request,162 stream=stream,183 unmodified lines346 hooks = hooks,347 )348 prep = self.prepare_request(req)349 348- # Add param cookies to session cookies349- self.cookies = merge_cookies(self.cookies, cookies)350-350 proxies = proxies or {}351 352 # Gather clues from the surrounding environment.353 if self.trust_env:199 unmodified linesmodified:requests/utils.py+64 added-5 removed
15 unmodified lines16 import os17 import platform18 import re19 import sys20+import socket21+import struct22 23 from . import __version__24 from . import certs25 from .compat import parse_http_list as _parse_list_header380 unmodified lines406 # or '%')407 return quote(unquote_unreserved(uri), safe="!#$%&'()*+,/:;=?@[]~")408 409 410+def address_in_network(ip, net):411+ """412+ This function allows you to check if on IP belongs to a network subnet413+ Example: returns True if ip = 192.168.1.1 and net = 192.168.1.0/24414+ returns False if ip = 192.168.1.1 and net = 192.168.100.0/24415+ """416+ ipaddr = struct.unpack('=L', socket.inet_aton(ip))[0]417+ netaddr, bits = net.split('/')418+ netmask = struct.unpack('=L', socket.inet_aton(dotted_netmask(int(bits))))[0]419+ network = struct.unpack('=L', socket.inet_aton(netaddr))[0] & netmask420+ return (ipaddr & netmask) == (network & netmask)421+422+423+def dotted_netmask(mask):424+ """425+ Converts mask from /xx format to xxx.xxx.xxx.xxx426+ Example: if mask is 24 function returns 255.255.255.0427+ """428+ bits = 0xffffffff ^ (1 << 32 - mask) - 1429+ return socket.inet_ntoa(struct.pack('>I', bits))430+431+432+def is_ipv4_address(string_ip):433+ try:434+ socket.inet_aton(string_ip)435+ except socket.error:436+ return False437+ return True438+439+440+def is_valid_cidr(string_network):441+ """Very simple check of the cidr format in no_proxy variable"""442+ if string_network.count('/') == 1:443+ try:444+ mask = int(string_network.split('/')[1])445+ except ValueError:446+ return False447+448+ if mask < 1 or mask > 32:449+ return False450+451+ try:452+ socket.inet_aton(string_network.split('/')[0])453+ except socket.error:454+ return False455+ else:456+ return False457+ return True458+459+460 def get_environ_proxies(url):461 """Return a dict of environment proxies."""462 463 get_proxy = lambda k: os.environ.get(k) or os.environ.get(k.upper())7 unmodified lines471 # We need to check whether we match here. We need to see if we match472 # the end of the netloc, both with and without the port.473 no_proxy = no_proxy.replace(' ', '').split(',')474 475+ ip = netloc.split(':')[0]476+ if is_ipv4_address(ip):477+ for proxy_ip in no_proxy:478+ if is_valid_cidr(proxy_ip):479+ if address_in_network(ip, proxy_ip):480+ return {}481+ else:423- for host in no_proxy:424- if netloc.endswith(host) or netloc.split(':')[0].endswith(host):425- # The URL does match something in no_proxy, so we don't want426- # to apply the proxies on this URL.427- return {}482+ for host in no_proxy:483+ if netloc.endswith(host) or netloc.split(':')[0].endswith(host):484+ # The URL does match something in no_proxy, so we don't want485+ # to apply the proxies on this URL.486+ return {}487 488 # If the system proxy settings indicate that this URL should be bypassed,489 # don't proxy.490 if proxy_bypass(netloc):153 unmodified linesmodified:AUTHORS.rst+1 added
141 unmodified lines142 - Can Ibanoglu <can.ibanoglu@gmail.com> @canibanoglu143 - Thomas Weißschuh <thomas@t-8ch.de> @t-8ch144 - Jayson Vantuyl <jayson@aggressive.ly> @kagato145 - Pengfei.X <pengphy@gmail.com>146+- Kamil Madac <kamil.madac@gmail.com>modified:test_requests.py+48 added-1 removed
163 unmodified lines164 assert s.cookies['foo'] == '"bar:baz"'165 166 def test_cookie_persists_via_api(self):167 s = requests.session()168- r = s.get(httpbin('redirect/1'), cookies={'foo':'bar'})168+ r = s.get(httpbin('redirect/1'), cookies={'foo': 'bar'})169 assert 'foo' in r.request.headers['Cookie']170 assert 'foo' in r.history[0].request.headers['Cookie']171 172 def test_request_cookie_overrides_session_cookie(self):3 unmodified lines176 assert r.json()['cookies']['foo'] == 'baz'177 # Session cookie should not be modified178 assert s.cookies['foo'] == 'bar'179 180+ def test_request_cookies_not_persisted(self):181+ s = requests.session()182+ s.get(httpbin('cookies'), cookies={'foo': 'baz'})183+ # Sending a request with cookies should not add cookies to the session184+ assert not s.cookies185+186 def test_generic_cookiejar_works(self):187 cj = cookielib.CookieJar()188 cookiejar_from_dict({'foo': 'bar'}, cj)189 s = requests.session()772 unmodified lines962 pass963 else:964 assert super_len(cStringIO.StringIO('but some how, some way...')) == 25965 966+ def test_get_environ_proxies_ip_ranges(self):967+ """ Ensures that IP addresses are correctly matches with ranges in no_proxy variable """968+ from requests.utils import get_environ_proxies969+ os.environ['no_proxy'] = "192.168.0.0/24,127.0.0.1,localhost.localdomain,172.16.1.1"970+ assert get_environ_proxies('http://192.168.0.1:5000/') == {}971+ assert get_environ_proxies('http://192.168.0.1/') == {}972+ assert get_environ_proxies('http://172.16.1.1/') == {}973+ assert get_environ_proxies('http://172.16.1.1:5000/') == {}974+ assert get_environ_proxies('http://192.168.1.1:5000/') != {}975+ assert get_environ_proxies('http://192.168.1.1/') != {}976+977+ def test_get_environ_proxies(self):978+ """ Ensures that IP addresses are correctly matches with ranges in no_proxy variable """979+ from requests.utils import get_environ_proxies980+ os.environ['no_proxy'] = "127.0.0.1,localhost.localdomain,192.168.0.0/24,172.16.1.1"981+ assert get_environ_proxies('http://localhost.localdomain:5000/v1.0/') == {}982+ assert get_environ_proxies('http://www.requests.com/') != {}983+984+ def test_is_ipv4_address(self):985+ from requests.utils import is_ipv4_address986+ assert is_ipv4_address('8.8.8.8')987+ assert not is_ipv4_address('8.8.8.8.8')988+ assert not is_ipv4_address('localhost.localdomain')989+990+ def test_is_valid_cidr(self):991+ from requests.utils import is_valid_cidr992+ assert not is_valid_cidr('8.8.8.8')993+ assert is_valid_cidr('192.168.1.0/24')994+995+ def test_dotted_netmask(self):996+ from requests.utils import dotted_netmask997+ assert dotted_netmask(8) == '255.0.0.0'998+ assert dotted_netmask(24) == '255.255.255.0'999+ assert dotted_netmask(25) == '255.255.255.128'1000+1001+ def test_address_in_network(self):1002+ from requests.utils import address_in_network1003+ assert address_in_network('192.168.1.1', '192.168.1.0/24')1004+ assert not address_in_network('172.16.0.1', '192.168.1.0/24')1005+1006+1007 if __name__ == '__main__':1008 unittest.main()