From 4372e32146bbe6731990d3f649847669807bfb84 Mon Sep 17 00:00:00 2001 From: Tricia <95389395+asymmetricia@users.noreply.github.com> Date: Fri, 9 Dec 2022 02:37:13 -0800 Subject: [PATCH] Retry Nanoleaf requests (#7) Implement three retries for all requests. --- aionanoleaf/nanoleaf.py | 35 ++++++++++++++++++++++++----------- setup.py | 2 +- 2 files changed, 25 insertions(+), 12 deletions(-) diff --git a/aionanoleaf/nanoleaf.py b/aionanoleaf/nanoleaf.py index 51f2fa0..d516dfd 100644 --- a/aionanoleaf/nanoleaf.py +++ b/aionanoleaf/nanoleaf.py @@ -30,7 +30,6 @@ ClientResponse, ClientSession, ClientTimeout, - ServerDisconnectedError, ClientConnectionError, ) @@ -67,12 +66,14 @@ def __init__( host: str, auth_token: str | None = None, port: int = 16021, + retries: int = 3, ) -> None: """Initialize the Nanoleaf.""" self._session = session self._host = host self._auth_token = auth_token self._port = port + self._retries = 3 @property def host(self) -> str: @@ -223,20 +224,32 @@ async def _request( """Make an authorized request to Nanoleaf with an auth_token.""" url = f"{self._api_url}/{self.auth_token}/{path}" json_data = json.dumps(data) - try: + err = None + # try self._retries times and only then raise an exception if we failed + for attempt in range(self._retries): try: resp = await self._session.request( method, url, data=json_data, timeout=self._REQUEST_TIMEOUT ) - except ServerDisconnectedError: - # Retry request once if the device disconnected - resp = await self._session.request( - method, url, data=json_data, timeout=self._REQUEST_TIMEOUT - ) - except ClientConnectionError as err: - raise Unavailable from err - except asyncio.TimeoutError as err: - raise Unavailable from err + # it worked (or 401, but that's a hard fail), so clear any + # previous error + err = None + break + except Exception as e: + err = e + + # did it work after retries? + if err is not None: + # no. we had an error; perform desired error handling (converting + # certain exceptions to Unavailable) and otherwise let it percolate + # upward. + try: + raise err + except ClientConnectionError as err: + raise Unavailable from err + except asyncio.TimeoutError as err: + raise Unavailable from err + if resp.status == 401: raise InvalidToken resp.raise_for_status() diff --git a/setup.py b/setup.py index 974b724..8a55899 100644 --- a/setup.py +++ b/setup.py @@ -5,7 +5,7 @@ setup( name="aionanoleaf", - version="0.2.0", + version="0.2.1", author="Milan Meulemans", author_email="milan.meulemans@live.be", description="Async Python package for the Nanoleaf API",