From b41dfaa594c1805886bdc1c4457df6584f9d073e Mon Sep 17 00:00:00 2001 From: David Sangrey Date: Fri, 17 Nov 2023 11:51:41 -0500 Subject: [PATCH] [2051] Don't Overwrite Every Session Whoops. Only fetch a new session if it's None. Co-Authored-By: Phoebe <40956085+C1701D@users.noreply.github.com> --- timeout_session.py | 23 +++++++++++------------ 1 file changed, 11 insertions(+), 12 deletions(-) diff --git a/timeout_session.py b/timeout_session.py index 2d0d395f1..55fc4dc0e 100644 --- a/timeout_session.py +++ b/timeout_session.py @@ -7,8 +7,7 @@ """ from __future__ import annotations -import requests -from requests import Session +from requests import Session, Response from requests.adapters import HTTPAdapter from config import user_agent @@ -25,7 +24,7 @@ def __init__(self, timeout: int, *args, **kwargs): super().__init__(*args, **kwargs) - def send(self, *args, **kwargs) -> requests.Response: + def send(self, *args, **kwargs) -> Response: """Send, but with a timeout always set.""" if kwargs["timeout"] is None: kwargs["timeout"] = self.default_timeout @@ -33,9 +32,7 @@ def send(self, *args, **kwargs) -> requests.Response: return super().send(*args, **kwargs) -def new_session( - timeout: int = REQUEST_TIMEOUT, session: requests.Session | None = None -) -> requests.Session: +def new_session(timeout: int = REQUEST_TIMEOUT, session: Session | None = None) -> Session: """ Create a new requests.Session and override the default HTTPAdapter with a TimeoutAdapter. @@ -43,9 +40,11 @@ def new_session( :param session: the Session object to attach the Adapter to, defaults to a new session :return: The created Session """ - with Session() as session: - session.headers['User-Agent'] = user_agent - adapter = TimeoutAdapter(timeout) - session.mount("http://", adapter) - session.mount("https://", adapter) - return session + session = session or Session() + session.headers.setdefault("User-Agent", user_agent) + + adapter = TimeoutAdapter(timeout) + for prefix in ("http://", "https://"): + session.mount(prefix, adapter) + + return session