Skip to content
Myr

address connection leak issue from #520

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

* prefetch now defaults to True, ensuring that by default, sockets are returned to the urllib3 connection pool on request end * sessions now have a close() method, notifying urllib3 to close pooled connections * the module-level API, e.g., `requests.get('http://www.google.com')`, explicitly closes its session when finished When prefetch is False, the open socket becomes part of the state of the Response object, and it's the client's responsibility to read the whole body, at which point the socket will be returned to the pool.

authored by Shivaram Lingamneni · committed by Shivaram Lingamneni · parent 9abc9ad · Browse files · 5 files+59 added−14 removed
This commit

State

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

Diff stats

5 files+59 added−14 removed

  • tests:+30 added−4 removed
  • other:+29 added−10 removed

5 files+59 added−14 removed

modified:requests/api.py+12 added-3 removed
36 unmodified lines
37 :param prefetch: (optional) if ``True``, the response content will be immediately downloaded.38 :param cert: (optional) if String, path to ssl client cert file (.pem). If Tuple, ('cert', 'key') pair.39 """4041 s = kwargs.pop('session') if 'session' in kwargs else sessions.session()42 return s.request(method=method, url=url, **kwargs)41 # if this session was passed in, leave it open (and retain pooled connections);42 # if we're making it just for this call, then close it when we're done.43 adhoc_session = False44 session = kwargs.pop('session', None)45 if session is None:46 session = sessions.session()47 adhoc_session = True4849 try:50 return session.request(method=method, url=url, **kwargs)51 finally:52 if adhoc_session:53 session.close()544555def get(url, **kwargs):56 """Sends a GET request. Returns :class:`Response` object.5758 :param url: URL for the new :class:`Request` object.
70 unmodified lines
modified:requests/models.py+4 added-2 removed
55 unmodified lines
56 allow_redirects=False,57 proxies=None,58 hooks=None,59 config=None,60 prefetch=False,60 prefetch=True,61 _poolmanager=None,62 verify=None,63 session=None,64 cert=None):
392 unmodified lines
457 return True458 except ValueError:459 return False460461 def send(self, anyway=False, prefetch=False):461 def send(self, anyway=False, prefetch=True):462 """Sends the request. Returns True if successful, False if not.463 If there was an HTTPError during transmission,464 self.response.status_code will contain the HTTPError code.465
307 unmodified lines
773 except AttributeError:774 self._content = None775776 self._content_consumed = True777 # don't need to release the connection; that's been handled by urllib3778 # since we exhausted the data.779 return self._content780781 @property782 def text(self):
63 unmodified lines
modified:requests/sessions.py+13 added-5 removed
64 unmodified lines
65 proxies=None,66 hooks=None,67 params=None,68 config=None,69 prefetch=False,69 prefetch=True,70 verify=True,71 cert=None):7273 self.headers = headers or {}
30 unmodified lines
104 def __enter__(self):105 return self106107 def __exit__(self, *args):108 pass108 self.close()109110 def close(self):111 """Dispose of any internal state.112113 Currently, this just closes the PoolManager, which closes pooled114 connections.115 """116 self.poolmanager.clear()117118 def request(self, method, url,119 params=None,120 data=None,121 headers=None,
5 unmodified lines
127 proxies=None,128 hooks=None,129 return_response=True,130 config=None,123 prefetch=False,131 prefetch=None,132 verify=None,133 cert=None):134135 """Constructs and sends a :class:`Request <Request>`.
11 unmodified lines
147 :param allow_redirects: (optional) Boolean. Set to True by default.148 :param proxies: (optional) Dictionary mapping protocol to the URL of the proxy.149 :param return_response: (optional) If False, an un-sent Request object will returned.150 :param config: (optional) A configuration dictionary. See ``request.defaults`` for allowed keys and their default values.143 :param prefetch: (optional) if ``True``, the response content will be immediately downloaded.151 :param prefetch: (optional) whether to immediately download the response content. Defaults to ``True``.152 :param verify: (optional) if ``True``, the SSL cert will be verified. A CA_BUNDLE path can also be provided.153 :param cert: (optional) if String, path to ssl client cert file (.pem). If Tuple, ('cert', 'key') pair.154 """155
4 unmodified lines
160 files = {} if files is None else files161 headers = {} if headers is None else headers162 params = {} if params is None else params163 hooks = {} if hooks is None else hooks156 prefetch = self.prefetch or prefetch164 prefetch = prefetch if prefetch is not None else self.prefetch165166 # use session's hooks as defaults167 for key, cb in list(self.hooks.items()):168 hooks.setdefault(key, cb)
164 unmodified lines
added:tests/informal/test_leaked_connections.py+26 added
1"""2This is an informal test originally written by Bluehorn;3it verifies that Requests does not leak connections when4the body of the request is not read.5"""67import gc, os, subprocess, requests, sys89def main():10 gc.disable()1112 for x in range(20):13 requests.head("http://www.google.com/")1415 print("Open sockets after 20 head requests:")16 pid = os.getpid()17 subprocess.call("lsof -p%d -a -iTCP" % (pid,), shell=True)1819 gcresult = gc.collect()20 print("Garbage collection result: %s" % (gcresult,))2122 print("Open sockets after garbage collection:")23 subprocess.call("lsof -p%d -a -iTCP" % (pid,), shell=True)2425if __name__ == '__main__':26 sys.exit(main())
modified:tests/test_requests.py+4 added-4 removed
805 unmodified lines
806 c = json.loads(r.text).get('cookies')807 assert 'k' in c808809 ds1 = pickle.loads(pickle.dumps(requests.session()))810 ds2 = pickle.loads(pickle.dumps(requests.session(prefetch=True)))811 assert not ds1.prefetch812 assert ds2.prefetch810 ds2 = pickle.loads(pickle.dumps(requests.session(prefetch=False)))811 assert ds1.prefetch812 assert not ds2.prefetch813814 # def test_invalid_content(self):815 # # WARNING: if you're using a terrible DNS provider (comcast),816 # # this will fail.
40 unmodified lines
857 '''\tUntent his person and share the air with us?'''858 )859860 # Make a request and monkey-patch its contents861 r = get(httpbin('get'))861 r = get(httpbin('get'), prefetch=False)862 r.raw = StringIO(quote)863864 lines = list(r.iter_lines())865 len_lines = len(lines)
101 unmodified lines