Merge pull request #760 from slingamn/fix_leak.release
Before adoption: this commit came in with the history the project adopted, so no landing records it.
address connection leak issue from #520
authored by Kenneth Reitz · committed by Kenneth Reitz · parents 1898077, 3c0b940 · 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
Provenance
- Commit
b13c24d- Tree
6db3624- Author
Kenneth Reitz <me@kennethreitz.com>- Committer
Kenneth Reitz <me@kennethreitz.com>- Parent 1
1898077- Parent 2
3c0b940
5 files changed+59 added−14 removed
modified:requests/api.py+12 added-3 removed
36 unmodified lines37 :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 """40 41- 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 = True48 49+ try:50+ return session.request(method=method, url=url, **kwargs)51+ finally:52+ if adhoc_session:53+ session.close()54 45-55 def get(url, **kwargs):56 """Sends a GET request. Returns :class:`Response` object.57 58 :param url: URL for the new :class:`Request` object.70 unmodified linesmodified:requests/models.py+4 added-2 removed
55 unmodified lines56 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 lines457 return True458 except ValueError:459 return False460 461- 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 lines773 except AttributeError:774 self._content = None775 776 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._content780 781 @property782 def text(self):63 unmodified linesmodified:requests/sessions.py+13 added-5 removed
64 unmodified lines65 proxies=None,66 hooks=None,67 params=None,68 config=None,69- prefetch=False,69+ prefetch=True,70 verify=True,71 cert=None):72 73 self.headers = headers or {}30 unmodified lines104 def __enter__(self):105 return self106 107 def __exit__(self, *args):108- pass108+ self.close()109 110+ def close(self):111+ """Dispose of any internal state.112+113+ Currently, this just closes the PoolManager, which closes pooled114+ connections.115+ """116+ self.poolmanager.clear()117+118 def request(self, method, url,119 params=None,120 data=None,121 headers=None,5 unmodified lines127 proxies=None,128 hooks=None,129 return_response=True,130 config=None,123- prefetch=False,131+ prefetch=None,132 verify=None,133 cert=None):134 135 """Constructs and sends a :class:`Request <Request>`.11 unmodified lines147 :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 lines160 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.prefetch165 166 # use session's hooks as defaults167 for key, cb in list(self.hooks.items()):168 hooks.setdefault(key, cb)164 unmodified linesadded:tests/informal/test_leaked_connections.py+26 added
1+"""2+This is an informal test originally written by Bluehorn;3+it verifies that Requests does not leak connections when4+the body of the request is not read.5+"""6+7+import gc, os, subprocess, requests, sys8+9+def main():10+ gc.disable()11+12+ for x in range(20):13+ requests.head("http://www.google.com/")14+15+ print("Open sockets after 20 head requests:")16+ pid = os.getpid()17+ subprocess.call("lsof -p%d -a -iTCP" % (pid,), shell=True)18+19+ gcresult = gc.collect()20+ print("Garbage collection result: %s" % (gcresult,))21+22+ print("Open sockets after garbage collection:")23+ subprocess.call("lsof -p%d -a -iTCP" % (pid,), shell=True)24+25+if __name__ == '__main__':26+ sys.exit(main())modified:tests/test_requests.py+4 added-4 removed
805 unmodified lines806 c = json.loads(r.text).get('cookies')807 assert 'k' in c808 809 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.prefetch813 814 # def test_invalid_content(self):815 # # WARNING: if you're using a terrible DNS provider (comcast),816 # # this will fail.40 unmodified lines857 '''\tUntent his person and share the air with us?'''858 )859 860 # Make a request and monkey-patch its contents861- r = get(httpbin('get'))861+ r = get(httpbin('get'), prefetch=False)862 r.raw = StringIO(quote)863 864 lines = list(r.iter_lines())865 len_lines = len(lines)119 unmodified lines