Skip to content

Commit

Permalink
Only init session once on HTTP
Browse files Browse the repository at this point in the history
  • Loading branch information
EvieePy committed Dec 23, 2024
1 parent 08ce6cc commit 629056f
Show file tree
Hide file tree
Showing 3 changed files with 12 additions and 3 deletions.
3 changes: 2 additions & 1 deletion twitchio/authentication/oauth.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@
from typing import TYPE_CHECKING, ClassVar

from ..http import HTTPClient, Route
from ..utils import MISSING
from .payloads import *


Expand All @@ -55,7 +56,7 @@ def __init__(
client_secret: str,
redirect_uri: str | None = None,
scopes: Scopes | None = None,
session: aiohttp.ClientSession | None = None,
session: aiohttp.ClientSession = MISSING,
) -> None:
super().__init__(session=session, client_id=client_id)

Expand Down
3 changes: 2 additions & 1 deletion twitchio/authentication/tokens.py
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@
from ..exceptions import HTTPException, InvalidTokenException
from ..http import HTTPAsyncIterator, PaginatedConverter
from ..types_.tokens import TokenMappingData
from ..utils import MISSING
from .oauth import OAuth
from .payloads import ClientCredentialsPayload, ValidateTokenPayload
from .scopes import Scopes
Expand All @@ -61,7 +62,7 @@ def __init__(
client_secret: str,
redirect_uri: str | None = None,
scopes: Scopes | None = None,
session: aiohttp.ClientSession | None = None,
session: aiohttp.ClientSession = MISSING,
nested_key: str | None = None,
) -> None:
super().__init__(
Expand Down
9 changes: 8 additions & 1 deletion twitchio/http.py
Original file line number Diff line number Diff line change
Expand Up @@ -377,11 +377,12 @@ async def __anext__(self) -> T:


class HTTPClient:
__slots__ = ("_client_id", "_session", "_should_close", "user_agent")
__slots__ = ("_client_id", "_session", "_session_set", "_should_close", "user_agent")

def __init__(self, session: aiohttp.ClientSession = MISSING, *, client_id: str) -> None:
self._session: aiohttp.ClientSession = session
self._should_close: bool = session is MISSING
self._session_set: bool = False

self._client_id: str = client_id

Expand All @@ -395,6 +396,11 @@ def headers(self) -> dict[str, str]:
return {"User-Agent": self.user_agent, "Client-ID": self._client_id}

async def _init_session(self) -> None:
if self._session_set:
return

self._session_set = True

if self._session is not MISSING:
self._session.headers.update(self.headers)
return
Expand All @@ -408,6 +414,7 @@ def clear(self) -> None:
"Clearing %s session. A new session will be created on the next request.", self.__class__.__qualname__
)
self._session = MISSING
self._session_set = False

async def close(self) -> None:
if not self._should_close:
Expand Down

0 comments on commit 629056f

Please sign in to comment.