refactoring

This commit is contained in:
petergardfjall 2014-11-12 16:12:33 +01:00
parent 4789ebe3e4
commit d17df2fc6c
4 changed files with 60 additions and 35 deletions

View File

@ -61,7 +61,7 @@ if __name__ == "__main__":
for index, id in enumerate(activity_ids): for index, id in enumerate(activity_ids):
log.info("processing activity {} ({} out of {}) ...".format( log.info("processing activity {} ({} out of {}) ...".format(
id, index+1, len(activity_ids))) id, index+1, len(activity_ids)))
garminexport.util.save_activity( garminexport.util.export_activity(
client, id, args.destination) client, id, args.destination)
except Exception as e: except Exception as e:
exc_type, exc_value, exc_traceback = sys.exc_info() exc_type, exc_value, exc_traceback = sys.exc_info()

View File

@ -6,9 +6,12 @@ import json
from datetime import datetime from datetime import datetime
import os import os
def save_activity(client, activity_id, destination): export_formats=["json_summary", "json_details", "gpx", "tcx", "fit"]
"""Downloads a certain Garmin Connect activity and saves it
to a given destination directory. def export_activity(client, activity_id, destination,
formats=None):
"""Exports a Garmin Connect activity to a given set of formats
and saves the result file(es) to a given destination directory.
:param client: A :class:`garminexport.garminclient.GarminClient` :param client: A :class:`garminexport.garminclient.GarminClient`
instance that is assumed to be connected. instance that is assumed to be connected.
@ -18,36 +21,51 @@ def save_activity(client, activity_id, destination):
:param destination: Destination directory (assumed to exist already). :param destination: Destination directory (assumed to exist already).
:type destination: str :type destination: str
:keyword formats: Which format(s) to export to. Could be any
of: 'json_summary', 'json_details', 'gpx', 'tcx', 'fit'.
If set to :obj:`None` all formats will be exported.
:type formats: list of str
""" """
if formats is None:
formats = ['json_summary', 'json_details', 'gpx', 'tcx', 'fit']
activity_summary = client.get_activity_summary(activity_id) activity_summary = client.get_activity_summary(activity_id)
activity_details = client.get_activity_details(activity_id)
activity_gpx = client.get_activity_gpx(activity_id)
activity_tcx = client.get_activity_tcx(activity_id)
activity_fit = client.get_activity_fit(activity_id)
# save activitity summary, details and GPX, TCX and FIT file. # prefix saved activity files with timestamp and activity id
creation_millis = activity_summary["activity"]["uploadDate"]["millis"] creation_millis = activity_summary["activity"]["uploadDate"]["millis"]
timestamp = datetime.fromtimestamp(int(creation_millis)/1000.0) timestamp = datetime.fromtimestamp(int(creation_millis)/1000.0)
filename_prefix = "{}_{}".format( filename_prefix = "{}_{}".format(
timestamp.strftime("%Y%m%d-%H%M%S"), activity_id) timestamp.strftime("%Y%m%d-%H%M%S"), activity_id)
path_prefix = os.path.join(destination, filename_prefix) path_prefix = os.path.join(destination, filename_prefix)
summary_file = path_prefix + "_summary.json" if 'json_summary' in formats:
details_file = path_prefix + "_details.json" summary_file = path_prefix + "_summary.json"
gpx_file = path_prefix + ".gpx" with codecs.open(summary_file, encoding="utf-8", mode="w") as f:
tcx_file = path_prefix + ".tcx" f.write(json.dumps(
fit_file = path_prefix + ".fit" activity_summary, ensure_ascii=False, indent=4))
with codecs.open(summary_file, encoding="utf-8", mode="w") as f:
f.write(json.dumps( if 'json_details' in formats:
activity_summary, ensure_ascii=False, indent=4)) activity_details = client.get_activity_details(activity_id)
with codecs.open(details_file, encoding="utf-8", mode="w") as f: details_file = path_prefix + "_details.json"
f.write(json.dumps( with codecs.open(details_file, encoding="utf-8", mode="w") as f:
activity_details, ensure_ascii=False, indent=4)) f.write(json.dumps(
with codecs.open(gpx_file, encoding="utf-8", mode="w") as f: activity_details, ensure_ascii=False, indent=4))
f.write(activity_gpx)
with codecs.open(tcx_file, encoding="utf-8", mode="w") as f: if 'gpx' in formats:
f.write(activity_tcx) activity_gpx = client.get_activity_gpx(activity_id)
if activity_fit: gpx_file = path_prefix + ".gpx"
with open(fit_file, mode="wb") as f: with codecs.open(gpx_file, encoding="utf-8", mode="w") as f:
f.write(activity_fit) f.write(activity_gpx)
if 'tcx' in formats:
activity_tcx = client.get_activity_tcx(activity_id)
tcx_file = path_prefix + ".tcx"
with codecs.open(tcx_file, encoding="utf-8", mode="w") as f:
f.write(activity_tcx)
if 'fit' in formats:
activity_fit = client.get_activity_fit(activity_id)
fit_file = path_prefix + ".fit"
if activity_fit:
with open(fit_file, mode="wb") as f:
f.write(activity_fit)

View File

@ -23,7 +23,6 @@ LOG_LEVELS = {
} }
"""Command-line (string-based) log-level mapping to logging module levels.""" """Command-line (string-based) log-level mapping to logging module levels."""
if __name__ == "__main__": if __name__ == "__main__":
parser = argparse.ArgumentParser( parser = argparse.ArgumentParser(
@ -34,6 +33,10 @@ if __name__ == "__main__":
"username", metavar="<username>", type=str, help="Account user name.") "username", metavar="<username>", type=str, help="Account user name.")
parser.add_argument( parser.add_argument(
"activity", metavar="<activity>", type=int, help="Activity ID.") "activity", metavar="<activity>", type=int, help="Activity ID.")
parser.add_argument(
"format", metavar="<format>", type=str,
help="Export format (one of: {}).".format(
garminexport.util.export_formats))
# optional args # optional args
parser.add_argument( parser.add_argument(
@ -49,7 +52,12 @@ if __name__ == "__main__":
args = parser.parse_args() args = parser.parse_args()
if not args.log_level in LOG_LEVELS: if not args.log_level in LOG_LEVELS:
raise ValueError("Illegal log-level argument: {}".format(args.log_level)) raise ValueError("Illegal log-level argument: {}".format(
args.log_level))
if not args.format in garminexport.util.export_formats:
raise ValueError(
"Uncrecognized export format: '{}'. Must be one of {}".format(
args.format, garminexport.util.export_formats))
logging.root.setLevel(LOG_LEVELS[args.log_level]) logging.root.setLevel(LOG_LEVELS[args.log_level])
try: try:
@ -58,11 +66,10 @@ if __name__ == "__main__":
if not args.password: if not args.password:
args.password = getpass.getpass("Enter password: ") args.password = getpass.getpass("Enter password: ")
with GarminClient(args.username, args.password) as client: with GarminClient(args.username, args.password) as client:
log.info("fetching activity {} ...".format(args.activity)) log.info("fetching activity {} ...".format(args.activity))
garminexport.util.save_activity( garminexport.util.export_activity(
client, args.activity, args.destination) client, args.activity, args.destination, formats=[args.format])
except Exception as e: except Exception as e:
exc_type, exc_value, exc_traceback = sys.exc_info() exc_type, exc_value, exc_traceback = sys.exc_info()
log.error(u"failed with exception: %s", e) log.error(u"failed with exception: %s", e)

View File

@ -99,7 +99,7 @@ if __name__ == "__main__":
for index, id in enumerate(missing_activities): for index, id in enumerate(missing_activities):
log.info("backing up activity {} ({} out of {}) ...".format( log.info("backing up activity {} ({} out of {}) ...".format(
id, index+1, len(missing_activities))) id, index+1, len(missing_activities)))
garminexport.util.save_activity( garminexport.util.export_activity(
client, id, args.backup_dir) client, id, args.backup_dir)
except Exception as e: except Exception as e:
exc_type, exc_value, exc_traceback = sys.exc_info() exc_type, exc_value, exc_traceback = sys.exc_info()