close session if it won't be reused (#138)
* close session if it won't be reused
Spencer Phillip Young authored 4 years ago
GitHub committed 4 years ago
9 | 9 | """ |
10 | 10 | from functools import partial |
11 | 11 | import traceback |
12 | ||
12 | 13 | try: |
13 | 14 | import gevent |
14 | 15 | from gevent import monkey as curious_george |
20 | 21 | curious_george.patch_all(thread=False, select=False) |
21 | 22 | |
22 | 23 | from requests import Session |
23 | ||
24 | 24 | |
25 | 25 | __all__ = ( |
26 | 26 | 'map', 'imap', |
46 | 46 | self.session = kwargs.pop('session', None) |
47 | 47 | if self.session is None: |
48 | 48 | self.session = Session() |
49 | self._close = True | |
50 | else: | |
51 | self._close = False # don't close adapters after each request if the user provided the session | |
49 | 52 | |
50 | 53 | callback = kwargs.pop('callback', None) |
51 | 54 | if callback: |
72 | 75 | except Exception as e: |
73 | 76 | self.exception = e |
74 | 77 | self.traceback = traceback.format_exc() |
78 | finally: | |
79 | if self._close: | |
80 | # if we provided the session object, make sure we're cleaning up | |
81 | # because there's no sense in keeping it open at this point if it wont be reused | |
82 | self.session.close() | |
75 | 83 | return self |
76 | 84 | |
77 | 85 |