11"""API client for Life Time Fitness"""
2- from aiohttp import ClientError , ClientResponseError , ClientConnectionError
2+ from aiohttp import ClientSession , ClientError , ClientResponseError , ClientConnectionError
33from datetime import date
44from http import HTTPStatus
55import logging
66
7- from homeassistant .helpers .aiohttp_client import async_create_clientsession
8-
97from .const import (
108 API_AUTH_ENDPOINT ,
119 API_AUTH_REQUEST_USERNAME_JSON_KEY ,
@@ -54,10 +52,10 @@ def handle_authentication_response_json(response_json: dict):
5452
5553
5654class Api :
57- def __init__ (self , hass , username : str , password : str ) -> None :
55+ def __init__ (self , client_session : ClientSession , username : str , password : str ) -> None :
5856 self ._username = username
5957 self ._password = password
60- self ._clientsession = async_create_clientsession ( hass )
58+ self ._client_session = client_session
6159 self ._sso_token = None
6260
6361 self .update_successful = True
@@ -68,7 +66,7 @@ def get_username(self):
6866
6967 async def authenticate (self ):
7068 try :
71- async with self ._clientsession .post (
69+ async with self ._client_session .post (
7270 API_AUTH_ENDPOINT ,
7371 json = {
7472 API_AUTH_REQUEST_USERNAME_JSON_KEY : self ._username ,
@@ -94,12 +92,15 @@ async def _get_visits_between_dates(self, start_date: date, end_date: date):
9492 raise ApiAuthRequired
9593
9694 try :
97- async with self ._clientsession .get (
95+ async with self ._client_session .get (
9896 API_CLUB_VISITS_ENDPOINT_FORMATSTRING .format (
9997 start_date = start_date .strftime (API_CLUB_VISITS_ENDPOINT_DATE_FORMAT ),
10098 end_date = end_date .strftime (API_CLUB_VISITS_ENDPOINT_DATE_FORMAT ),
10199 ),
102- headers = {API_CLUB_VISITS_AUTH_HEADER : self ._sso_token },
100+ headers = {
101+ API_CLUB_VISITS_AUTH_HEADER : self ._sso_token ,
102+ API_AUTH_REQUEST_SUBSCRIPTION_KEY_HEADER : API_AUTH_REQUEST_SUBSCRIPTION_KEY_HEADER_VALUE
103+ },
103104 ) as response :
104105 response_json = await response .json ()
105106 return response_json
@@ -160,3 +161,18 @@ class ApiAuthRequired(Exception):
160161
161162class ApiAuthExpired (Exception ):
162163 """Authentication has expired"""
164+
165+
166+ # Test the API client by running this script with username and password:
167+ async def main ():
168+ import sys , aiohttp
169+ username , password = sys .argv [1 :]
170+ async with aiohttp .ClientSession () as client_session :
171+ api = Api (client_session , username , password )
172+ await api .authenticate ()
173+ await api .update ()
174+ print (api .result_json )
175+
176+ if __name__ == "__main__" :
177+ import asyncio
178+ asyncio .run (main ())
0 commit comments