Hi all,
I am trying to run a Python Script for getting the live count of members at my gym. I am able to run the script fine on my own laptop. However I am unsure as to how to properly get it running in AppDameon.
The original Python Script is from here: GitHub Link
Any guidance on this would be very appreciated.
So far this is what I have tried:
Apps.yaml:
puregym:
module: puregym
class: PuregymAPIClient
email: [WITHHELD FOR PRIVACY]
pin: [WITHHELD FOR PRIVACY]
PureGym.py:
import requests
import textdistance
import appdaemon.plugins.hass.hassapi as hass
class PuregymAPIClient(hass.Hass):
headers = {'Content-Type': 'application/x-www-form-urlencoded', 'User-Agent': 'PureGym/1523 CFNetwork/1312 Darwin/21.0.0'}
authed = False
home_gym_id = None
gyms = None
def initialize(self):
self.login(self.args["email"],self.args["pin"])
def login(self, email, pin):
self.session = requests.session()
data = {
'grant_type': 'password',
'username': 'email',
'password': 'pin',
'scope': 'pgcapi',
'client_id': 'ro.client'
}
response = self.session.post('https://auth.puregym.com/connect/token', headers=self.headers, data=data)
if response.status_code == 200:
self.auth_json = response.json()
self.authed = True
self.headers['Authorization'] = 'Bearer '+self.auth_json['access_token']
else:
return response.raise_for_status()
def get_list_of_gyms(self):
if not self.authed:
return PermissionError('Not authed: call login(email, pin)')
response = self.session.get(f'https://capi.puregym.com/api/v1/gyms/', headers=self.headers)
if response.status_code == 200:
self.gyms = {i['name'].replace(' ', '').replace('-', '').lower(): i['id'] for i in response.json()}
else:
return ValueError('Response '+str(response.status_code))
def get_gym(self, gym_name):
"""returns corrected gym name and its ID"""
gym_name = gym_name.replace(' ', '').replace('-', '').lower()
if self.gyms is None:
self.get_list_of_gyms()
return max(list(self.gyms.items()), key=lambda x: textdistance.levenshtein.similarity(gym_name, x[0]))
def get_home_gym(self):
if not self.authed:
return PermissionError('Not authed: call login(email, pin)')
response = self.session.get('https://capi.puregym.com/api/v1/member', headers=self.headers)
if response.status_code == 200:
self.home_gym_id = response.json()['homeGymId']
else:
return ValueError('Response '+str(response.status_code))
def get_gym_attendance(self, gym, return_name=False):
if not self.authed:
return PermissionError('Not authed: call login(email, pin)')
if gym is None:
if self.home_gym_id is None:
self.get_home_gym()
gym_id = self.home_gym_id
elif isinstance(gym, int):
gym_id = gym
gym = None
else:
gym, gym_id = self.get_gym(gym) # name->id
response = self.session.get(f'https://capi.puregym.com/api/v1/gyms/{gym_id}/attendance', headers=self.headers)
if response.status_code == 200:
n = response.json()['totalPeopleInGym']
if return_name:
return n, gym
return n
else:
return response.raise_for_status()
if __name__ == '__main__':
from argparse import ArgumentParser
parser = ArgumentParser()
parser.add_argument('email')
parser.add_argument('pin')
parser.add_argument('--gym', default=None)
args = parser.parse_args()
client = PuregymAPIClient()
client.login(args.email, args.pin)
print(client.get_gym_attendance(args.gym))
AppDameon Add-On Logs:
2022-05-06 11:16:30.063251 INFO AppDaemon: Reloading Module: /config/appdaemon/apps/puregym.py
2022-05-06 11:16:30.069682 INFO AppDaemon: Initializing app puregym using class PuregymAPIClient from module puregym
2022-05-06 11:16:37.199941 WARNING puregym: ------------------------------------------------------------
2022-05-06 11:16:37.200396 WARNING puregym: Unexpected error running initialize() for puregym 2022-05-06 11:16:37.200620 WARNING puregym: ------------------------------------------------------------
2022-05-06 11:16:37.201298 WARNING puregym: Traceback (most recent call last):
File "/usr/lib/python3.9/site-packages/appdaemon/app_management.py", line 165, in initialize_app await utils.run_in_executor(self, init)
File "/usr/lib/python3.9/site-packages/appdaemon/utils.py", line 337, in run_in_executor response = future.result() File "/usr/lib/python3.9/concurrent/futures/thread.py", line 52, in run result = self.fn(*self.args, **self.kwargs)
File "/config/appdaemon/apps/puregym.py", line 13, in initialize self.login(self.args["email"],self.args["pin"])
File "/config/appdaemon/apps/puregym.py", line 31, in login return response.raise_for_status()
File "/usr/lib/python3.9/site-packages/requests/models.py", line 953, in raise_for_status raise HTTPError(http_error_msg, response=self) requests.exceptions.HTTPError: 400 Client Error: Bad Request for url: https://auth.puregym.com/connect/token
2022-05-06 11:16:37.201611 WARNING puregym: ------------------------------------------------------------
2022-05-06 11:16:37.202664 WARNING AppDaemon: Excessive time spent in utility loop: 7149.0ms, 7149.0ms in check_app_updates(), 0.0ms in other