Skip to content

Commit

Permalink
Add auto-token renewal
Browse files Browse the repository at this point in the history
  • Loading branch information
kbickar committed Nov 29, 2022
1 parent 3f04bb9 commit 9538c73
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 4 deletions.
6 changes: 5 additions & 1 deletion sense_energy/asyncsenseable.py
Original file line number Diff line number Diff line change
Expand Up @@ -157,13 +157,17 @@ async def get_realtime_future(self, callback):
"""Returns an async Future to parse realtime data with callback"""
await self.async_realtime_stream(callback)

async def _api_call(self, url, payload={}):
async def _api_call(self, url, payload={}, retry=False):
"""Make a call to the Sense API directly and return the json results."""
timeout = aiohttp.ClientTimeout(total=self.api_timeout)
try:
async with self._client_session.get(
API_URL + url, headers=self.headers, timeout=timeout, data=payload
) as resp:
if not retry and resp.status == 401:
await self.renew_auth()
return await self._api_call(url, payload, True)

# 4xx represents unauthenticated
if resp.status == 401 or resp.status == 403 or resp.status == 404:
raise SenseAuthenticationException(f"API Return Code: {resp.status}")
Expand Down
15 changes: 12 additions & 3 deletions sense_energy/senseable.py
Original file line number Diff line number Diff line change
Expand Up @@ -153,15 +153,24 @@ def get_realtime_stream(self):
if ws:
ws.close()

def _api_call(self, url, payload={}):
def _api_call(self, url, payload={}, retry=False):
"""Make a call to the Sense API directly and return the json results."""
try:
return self.s.get(
resp = self.s.get(
API_URL + url,
headers=self.headers,
timeout=self.api_timeout,
params=payload,
).json()
)

if not retry and resp.status_code == 401:
self.renew_auth()
return self._api_call(url, payload, True)

# 4xx represents unauthenticated
if resp.status_code == 401 or resp.status_code == 403 or resp.status_code == 404:
raise SenseAuthenticationException("API Return Code: %s", resp.status_code)
return resp.json()
except ReadTimeout:
raise SenseAPITimeoutException("API call timed out")

Expand Down

0 comments on commit 9538c73

Please sign in to comment.