Skip to content

Commit

Permalink
[2051] Don't Overwrite Every Session
Browse files Browse the repository at this point in the history
Whoops. Only fetch a new session if it's None.

Co-Authored-By: Phoebe <[email protected]>
  • Loading branch information
Rixxan and C1701D committed Nov 17, 2023
1 parent ebd1813 commit b41dfaa
Showing 1 changed file with 11 additions and 12 deletions.
23 changes: 11 additions & 12 deletions timeout_session.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand All @@ -25,27 +24,27 @@ 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

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.
:param timeout: the timeout to set the TimeoutAdapter to, defaults to REQUEST_TIMEOUT
: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

0 comments on commit b41dfaa

Please sign in to comment.