Could you please give me some feedback on the use of class methods in this Python script?
The code retrieves time entries from the Toggl API and works as expected. My question is, do the methods make sense? The methods first_api_call and make_subsequent_calls change self.data. Is this okay or should all the changes to self.data be made in retrieve_data?
from datetime import datetime
import requests
today = datetime.today().date()
since = datetime(today.year, 1, 1)
class Toggl:
def __init__(self):
self.data = []
self.total_calls = None
self.params = {
'workspace_id': '5604761',
'since': since,
'until': today,
'user_agent': '[email protected]',
'page': 1,
}
def retrieve_data(self):
r = self.first_api_call()
self.total_calls = self.calculate_number_of_extra_calls_needed(r)
self.make_subsequent_calls()
def first_api_call(self):
r = requests.get('https://toggl.com/reports/api/v2/details',
params=self.params,
auth=('APIKEY', 'api_token'))
r.raise_for_status()
r = r.json()
self.data = r['data']
return r
def calculate_number_of_extra_calls_needed(self, r):
"""
Calculate the number of pages that need to be retrieved.
The second part is True/False to round up.
Finally minus 1 because we got the first page already.
"""
total_calls = r['total_count'] // 50 + (r['total_count'] % 50 > 0) - 1
return total_calls
def make_subsequent_calls(self):
"""Make the new API calls and store the data"""
for i in range(self.total_calls):
self.params['page'] = self.params['page'] + 1
r = requests.get('https://toggl.com/reports/api/v2/details',
params=self.params,
auth=('APIKEY', 'api_token'))
r.raise_for_status()
r = r.json()
for d in r['data']:
self.data.append(d)
if __name__ == "__main__":
toggl = Toggl()
toggl.retrieve_data()
print(toggl.data)