Skip to content
Merged
Show file tree
Hide file tree
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
23 changes: 10 additions & 13 deletions homeassistant_api/client.py
Original file line number Diff line number Diff line change
@@ -1,11 +1,12 @@
"""Module containing the primary Client class."""
import gc
import inspect
import logging
from typing import Any

from .rawasyncclient import RawAsyncClient
from .rawclient import RawClient

logger = logging.getLogger(__name__)


class Client(RawClient, RawAsyncClient):
"""
Expand All @@ -18,14 +19,10 @@ class Client(RawClient, RawAsyncClient):
:param async_cache_session: A :py:class:`aiohttp_client_cache.CachedSession` object to use for caching requests. Optional.
""" # pylint: disable=line-too-long

def __init__(self, *args: Any, **kwargs: Any) -> None:
assert (frame := inspect.currentframe()) is not None
assert (parent_frame := frame.f_back) is not None
try:
if inspect.iscoroutinefunction(
caller := gc.get_referrers(parent_frame.f_code)[0]
) or inspect.iscoroutine(caller):
RawAsyncClient.__init__(self, *args, **kwargs)
except IndexError: # pragma: no cover
pass
RawClient.__init__(self, *args, **kwargs)
def __init__(self, *args: Any, use_async: bool = False, **kwargs: Any) -> None:
if use_async:
logger.error("Initializing Client asyncsyncronously")
RawAsyncClient.__init__(self, *args, **kwargs)
else:
logger.error("Initializing Client syncronously")
RawClient.__init__(self, *args, **kwargs)
6 changes: 3 additions & 3 deletions homeassistant_api/rawasyncclient.py
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,7 @@ def __init__(
] = None, # Explicitly disable cache with async_cache_session=False
**kwargs,
):
super().__init__(*args, **kwargs)
RawBaseClient.__init__(self, *args, **kwargs)
if async_cache_session is False:
self.async_cache_session = aiohttp.ClientSession()
elif async_cache_session is None:
Expand All @@ -77,9 +77,9 @@ async def __aenter__(self):
await self.async_check_api_running()
return self

async def __aexit__(self, cls, obj, traceback):
async def __aexit__(self, _, __, ___):
logger.debug("Exiting async requests session %r", self.async_cache_session)
await self.async_cache_session.__aexit__(cls, obj, traceback)
await self.async_cache_session.close()

# Very important request function
async def async_request(
Expand Down
6 changes: 3 additions & 3 deletions homeassistant_api/rawclient.py
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@ def __init__(
] = None, # Explicitly disable cache with cache_session=False
**kwargs,
):
super().__init__(*args, **kwargs)
RawBaseClient.__init__(self, *args, **kwargs)
if cache_session is False:
self.cache_session = requests.Session()
elif cache_session is None:
Expand All @@ -74,9 +74,9 @@ def __enter__(self):
self.check_api_config()
return self

def __exit__(self, *args):
def __exit__(self, _, __, ___):
logger.debug("Exiting requests session %r", self.cache_session)
self.cache_session.__exit__(*args)
self.cache_session.close()

def request(
self,
Expand Down
7 changes: 5 additions & 2 deletions tests/conftest.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,8 @@
def setup_cached_client() -> Generator[Client, None, None]:
"""Initializes the Client and enters a cached session."""
with Client(
os.environ["HOMEASSISTANTAPI_URL"], os.environ["HOMEASSISTANTAPI_TOKEN"]
os.environ["HOMEASSISTANTAPI_URL"],
os.environ["HOMEASSISTANTAPI_TOKEN"],
) as client:
yield client

Expand All @@ -29,6 +30,8 @@ def event_loop():
async def setup_async_cached_client() -> AsyncGenerator[Client, None]:
"""Initializes the Client and enters an async cached session."""
async with Client(
os.environ["HOMEASSISTANTAPI_URL"], os.environ["HOMEASSISTANTAPI_TOKEN"]
os.environ["HOMEASSISTANTAPI_URL"],
os.environ["HOMEASSISTANTAPI_TOKEN"],
use_async=True,
) as client:
yield client
2 changes: 2 additions & 0 deletions tests/test_client.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@ async def test_custom_async_cached_session() -> None:
expire_after=10,
),
),
use_async=True,
):
pass

Expand All @@ -43,5 +44,6 @@ async def test_default_async_session() -> None:
os.environ["HOMEASSISTANTAPI_URL"],
os.environ["HOMEASSISTANTAPI_TOKEN"],
async_cache_session=False,
use_async=True,
):
pass
4 changes: 3 additions & 1 deletion tests/test_errors.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,9 @@ def test_unauthorized() -> None:
async def test_async_unauthorized() -> None:
with pytest.raises(UnauthorizedError):
async with Client(
os.environ["HOMEASSISTANTAPI_URL"], "lolthisisawrongtokenforsure"
os.environ["HOMEASSISTANTAPI_URL"],
"lolthisisawrongtokenforsure",
use_async=True,
):
pass

Expand Down