|
1 | 1 | import sys |
| 2 | +import threading |
2 | 3 | import requests |
3 | 4 | from base64 import encodebytes |
4 | 5 | import json |
@@ -58,6 +59,17 @@ def raise_exception_from_status(status, message=None): |
58 | 59 | def __init__(self, config, environment=None): |
59 | 60 | self.config = config |
60 | 61 | self.environment = environment or self.config.environment |
| 62 | + self._thread_local = threading.local() |
| 63 | + |
| 64 | + def _get_session(self): |
| 65 | + if not hasattr(self._thread_local, 'session'): |
| 66 | + self._thread_local.session = requests.Session() |
| 67 | + return self._thread_local.session |
| 68 | + |
| 69 | + def close(self): |
| 70 | + if hasattr(self._thread_local, 'session'): |
| 71 | + self._thread_local.session.close() |
| 72 | + del self._thread_local.session |
61 | 73 |
|
62 | 74 | def post(self, path, params=None): |
63 | 75 | return self._make_request("POST", path, Http.ContentType.Xml, params) |
@@ -113,22 +125,23 @@ def http_do(self, http_verb, path, headers, request_body): |
113 | 125 | else: |
114 | 126 | verify = self.environment.ssl_certificate |
115 | 127 |
|
116 | | - with requests.Session() as session: |
117 | | - request = requests.Request( |
118 | | - method=http_verb, |
119 | | - url=full_path, |
120 | | - headers=headers, |
121 | | - data=data, |
122 | | - files=files) |
123 | | - prepared_request = request.prepare() |
124 | | - prepared_request.url = full_path |
125 | | - # there's a bug in requests module that requires we manually update proxy settings, |
126 | | - # see https://github.com/psf/requests/issues/5677 |
127 | | - session.proxies.update(requests.utils.getproxies()) |
128 | | - |
129 | | - response = session.send(prepared_request, |
130 | | - verify=verify, |
131 | | - timeout=self.config.timeout) |
| 128 | + session = self._get_session() |
| 129 | + |
| 130 | + request = requests.Request( |
| 131 | + method=http_verb, |
| 132 | + url=full_path, |
| 133 | + headers=headers, |
| 134 | + data=data, |
| 135 | + files=files) |
| 136 | + prepared_request = request.prepare() |
| 137 | + prepared_request.url = full_path |
| 138 | + # there's a bug in requests module that requires we manually update proxy settings, |
| 139 | + # see https://github.com/psf/requests/issues/5677 |
| 140 | + session.proxies.update(requests.utils.getproxies()) |
| 141 | + |
| 142 | + response = session.send(prepared_request, |
| 143 | + verify=verify, |
| 144 | + timeout=self.config.timeout) |
132 | 145 |
|
133 | 146 | return [response.status_code, response.text] |
134 | 147 |
|
|
0 commit comments