Skip to content

api: Use requests.Session #18

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 1 commit into from
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
39 changes: 27 additions & 12 deletions zulip/zulip/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -285,6 +285,30 @@ def __init__(self, email=None, api_key=None, config_file=None,
self.client_cert = client_cert
self.client_cert_key = client_cert_key

self.session = None # type: Union[None, requests.Session]

def ensure_session(self):
# type: () -> None

# Check if the session has been created already, and return
# immediately if so.
if self.session:
return

# Build a client cert object for requests
if self.client_cert_key is not None:
client_cert = (self.client_cert, self.client_cert_key) # type: Union[str, Tuple[str, str]]
else:
client_cert = self.client_cert

# Actually construct the session
session = requests.Session()
session.auth = requests.auth.HTTPBasicAuth(self.email, self.api_key) # type: ignore # https://github.com/python/typeshed/pull/1504
session.verify = self.tls_verification # type: ignore # https://github.com/python/typeshed/pull/1504
session.cert = client_cert
session.headers = {"User-agent": self.get_user_agent()}
self.session = session

def get_user_agent(self):
# type: () -> str
vendor = ''
Expand Down Expand Up @@ -327,6 +351,8 @@ def do_api_query(self, orig_request, url, method="POST", longpolling=False, file
for f in files:
req_files.append((f.name, f))

self.ensure_session()

query_state = {
'had_error_retry': False,
'request': request,
Expand Down Expand Up @@ -370,21 +396,10 @@ def end_error_retry(succeeded):
if files:
kwargs['files'] = req_files

# Build a client cert object for requests
if self.client_cert_key is not None:
client_cert = (self.client_cert, self.client_cert_key) # type: Union[str, Tuple[str, str]]
else:
client_cert = self.client_cert

res = requests.request(
res = self.session.request(
method,
urllib.parse.urljoin(self.base_url, url),
auth=requests.auth.HTTPBasicAuth(self.email,
self.api_key),
verify=self.tls_verification,
cert=client_cert,
timeout=90,
headers={"User-agent": self.get_user_agent()},
**kwargs)

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