Skip to content

Commit d405ca1

Browse files
committed
api: Use requests.Session
Using requests.Session allows the requests library to reuse HTTP connections, which is potentially helpful for performance. This fixes python-zulip-api #3.
1 parent b08a37f commit d405ca1

File tree

1 file changed

+27
-12
lines changed

1 file changed

+27
-12
lines changed

zulip/zulip/__init__.py

+27-12
Original file line numberDiff line numberDiff line change
@@ -285,6 +285,30 @@ def __init__(self, email=None, api_key=None, config_file=None,
285285
self.client_cert = client_cert
286286
self.client_cert_key = client_cert_key
287287

288+
self.session = None # type: Union[None, requests.Session]
289+
290+
def _init_session(self):
291+
# type: () -> None
292+
293+
# Check if the session has been created already, and return
294+
# immediately if so.
295+
if self.session:
296+
return
297+
298+
# Build a client cert object for requests
299+
if self.client_cert_key is not None:
300+
client_cert = (self.client_cert, self.client_cert_key) # type: Union[str, Tuple[str, str]]
301+
else:
302+
client_cert = self.client_cert
303+
304+
# Actually construct the session
305+
session = requests.Session()
306+
session.auth = requests.auth.HTTPBasicAuth(self.email, self.api_key)
307+
session.verify = self.tls_verification
308+
session.cert = client_cert
309+
session.headers = {"User-agent": self.get_user_agent()}
310+
self.session = session
311+
288312
def get_user_agent(self):
289313
# type: () -> str
290314
vendor = ''
@@ -327,6 +351,8 @@ def do_api_query(self, orig_request, url, method="POST", longpolling=False, file
327351
for f in files:
328352
req_files.append((f.name, f))
329353

354+
self._init_session()
355+
330356
query_state = {
331357
'had_error_retry': False,
332358
'request': request,
@@ -370,21 +396,10 @@ def end_error_retry(succeeded):
370396
if files:
371397
kwargs['files'] = req_files
372398

373-
# Build a client cert object for requests
374-
if self.client_cert_key is not None:
375-
client_cert = (self.client_cert, self.client_cert_key) # type: Union[str, Tuple[str, str]]
376-
else:
377-
client_cert = self.client_cert
378-
379-
res = requests.request(
399+
res = self.session.request(
380400
method,
381401
urllib.parse.urljoin(self.base_url, url),
382-
auth=requests.auth.HTTPBasicAuth(self.email,
383-
self.api_key),
384-
verify=self.tls_verification,
385-
cert=client_cert,
386402
timeout=90,
387-
headers={"User-agent": self.get_user_agent()},
388403
**kwargs)
389404

390405
# On 50x errors, try again after a short sleep

0 commit comments

Comments
 (0)