fitbitエクササイズデータ (TCX) を列挙する その2
前回で、APIとしてのfitbit.activity_logs_list() は完成した。ただし、以下の点が気になるのでユーティリティ関数でも作ってみよう。
- activity_logs_list() は Web APIとして一度に巨大なデータを返さないpaginationの考え方に基づいており、一回の呼び出しでは最大20エントリーしか戻らない。これはふつうのプログラミングAPIとしては利用しにくい。
- 今回の用途では、logType = mobile_run である「明示的に記録したジョギング」エントリの log_id 一覧が欲しい。
よって、以下のような generator を作った。これで20エントリー以上あっても(時間はかかるが)fitbitサーバーから一気にデータを持ってくることができる。
def enumerate_activity_logs(auth2_client, log_type, from_date, to_date): """ enumerate activity logs with a certain log type. note this function works as a 'generator' which you can use in enumeration loop. Parameters ---------- auth2_client : fitbit.Fitbit web API client object log_type : str log type such as 'mobile_run'. See https://dev.fitbit.com/docs/activity/#get-activity-logs-list for more details. from_date : str The beginning date in the format yyyy-MM-ddTHH:mm:ss. Only yyyy-MM-dd is required. to_date : str The ending date in the format yyyy-MM-ddTHH:mm:ss. Only yyyy-MM-dd is required. Return (yield) -------------- act : 'Activity' map object map object which contains an Activity data. See https://dev.fitbit.com/docs/activity/#get-activity-logs-list for more details. """ response = auth2_client.activity_logs_list(after_date=from_date) enumerating = True while enumerating: for act in response['activities']: if act['startTime'] > to_date: enumerating = False break if act['logType'] == log_type: yield act if enumerating: next_request = response['pagination']['next'] response = auth2_client.make_request(next_request)
このユーティリティーは以下のようにして呼び出すことができ、きちんと自分のジョギング日時リストが取得できた。
"""for obtaining Access-token and Refresh-token""" server = Oauth2.OAuth2Server(USER_ID, CLIENT_SECRET) server.browser_authorize() """Authorization""" auth2_client = fitbit.Fitbit(USER_ID, CLIENT_SECRET, oauth2=True, access_token=server.oauth.token['access_token'], refresh_token=server.oauth.token['refresh_token']) for run in enumerate_activity_logs(auth2_client, 'mobile_run', '2016-12-01', '2017-01-01'): print(run['startTime'])