From 7307426ad4af2ebacc493c4d0818abd7f2ba4654 Mon Sep 17 00:00:00 2001 From: Spencer Phillip Young Date: Sun, 5 Apr 2020 07:24:03 -0700 Subject: [PATCH] close session if it won't be reused (#138) * close session if it won't be reused --- grequests.py | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/grequests.py b/grequests.py index 0ceab0f..f4ec5c7 100755 --- a/grequests.py +++ b/grequests.py @@ -10,6 +10,7 @@ """ from functools import partial import traceback + try: import gevent from gevent import monkey as curious_george @@ -22,7 +23,6 @@ from requests import Session - __all__ = ( 'map', 'imap', 'get', 'options', 'head', 'post', 'put', 'patch', 'delete', 'request' @@ -47,6 +47,9 @@ def __init__(self, method, url, **kwargs): self.session = kwargs.pop('session', None) if self.session is None: self.session = Session() + self._close = True + else: + self._close = False # don't close adapters after each request if the user provided the session callback = kwargs.pop('callback', None) if callback: @@ -73,6 +76,11 @@ def send(self, **kwargs): except Exception as e: self.exception = e self.traceback = traceback.format_exc() + finally: + if self._close: + # if we provided the session object, make sure we're cleaning up + # because there's no sense in keeping it open at this point if it wont be reused + self.session.close() return self