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