Skip to content

Commit 5eaac7b

Browse files
dehnerttimabbott
authored andcommitted
api: Use requests.Session.
Using requests.Session allows the requests library to reuse HTTP connections, which is potentially helpful for performance. Fixes zulip#3.
1 parent 749356d commit 5eaac7b

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
@@ -342,6 +342,30 @@ def __init__(self, email=None, api_key=None, config_file=None,
342342
self.client_cert = client_cert
343343
self.client_cert_key = client_cert_key
344344

345+
self.session = None # type: Union[None, requests.Session]
346+
347+
def ensure_session(self):
348+
# type: () -> None
349+
350+
# Check if the session has been created already, and return
351+
# immediately if so.
352+
if self.session:
353+
return
354+
355+
# Build a client cert object for requests
356+
if self.client_cert_key is not None:
357+
client_cert = (self.client_cert, self.client_cert_key) # type: Union[str, Tuple[str, str]]
358+
else:
359+
client_cert = self.client_cert
360+
361+
# Actually construct the session
362+
session = requests.Session()
363+
session.auth = requests.auth.HTTPBasicAuth(self.email, self.api_key) # type: ignore # https://github.com/python/typeshed/pull/1504
364+
session.verify = self.tls_verification # type: ignore # https://github.com/python/typeshed/pull/1504
365+
session.cert = client_cert
366+
session.headers = {"User-agent": self.get_user_agent()}
367+
self.session = session
368+
345369
def get_user_agent(self):
346370
# type: () -> str
347371
vendor = ''
@@ -384,6 +408,8 @@ def do_api_query(self, orig_request, url, method="POST", longpolling=False, file
384408
for f in files:
385409
req_files.append((f.name, f))
386410

411+
self.ensure_session()
412+
387413
query_state = {
388414
'had_error_retry': False,
389415
'request': request,
@@ -427,21 +453,10 @@ def end_error_retry(succeeded):
427453
if files:
428454
kwargs['files'] = req_files
429455

430-
# Build a client cert object for requests
431-
if self.client_cert_key is not None:
432-
client_cert = (self.client_cert, self.client_cert_key) # type: Union[str, Tuple[str, str]]
433-
else:
434-
client_cert = self.client_cert
435-
436-
res = requests.request(
456+
res = self.session.request(
437457
method,
438458
urllib.parse.urljoin(self.base_url, url),
439-
auth=requests.auth.HTTPBasicAuth(self.email,
440-
self.api_key),
441-
verify=self.tls_verification,
442-
cert=client_cert,
443459
timeout=90,
444-
headers={"User-agent": self.get_user_agent()},
445460
**kwargs)
446461

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

0 commit comments

Comments
 (0)