__author__ = 'tyrel' from django.core.management.base import BaseCommand, CommandError from django.contrib.auth.models import User from tracking.models import Track, Segment, Point import xmltodict import os class Command(BaseCommand): help = 'Import a gpx file' def add_arguments(self, parser): parser.add_argument('username', help="Username to import to.") parser.add_argument('filepath', help="File or directory to import a gpx file.") def handle(self, *args, **options): self.username = options['username'] filepath = options['filepath'] try: self.user = User.objects.get(username=self.username) except User.DoesNotExist: raise CommandError("User {0} does not exist".format(self.username)) if os.path.isdir(filepath): self.import_directory(filepath) elif os.path.isfile(filepath): self.import_file(filepath) else: raise CommandError("{0} is neither an existing file, nor a path.".format(filepath)) def import_directory(self, directory): pass def import_file(self, filename): with open(filename) as fd: obj = dict(xmltodict.parse(fd.read()))['gpx'] metadata = obj['metadata'] tracks = obj['trk'] start_time = metadata['time'] name = tracks['name'] segments = tracks['trkseg'] if isinstance(segments, list): raise NotImplemented( "Haven't run across one that has multiple segments. " "Contribute a patch if you have.") elif isinstance(segments, dict): # TODO: IF multiple import! track = Track.objects.create(user=self.user, start=start_time, name=name) points = segments['trkpt'] segment = Segment(track=track, time=points[0]['time']) segment.save() print len(points) for pt in points: Point.objects.create(segment=segment, time=pt['time'], elevation=pt['ele'], latitude=pt['@lat'], longitude=pt['@lon']) print "created Track <{0}> start: {1}, stop: {2}".format( track.name, track.start, track.finish ) def etree_to_dict(t): d = {t.tag: map(etree_to_dict, t.getchildren())} d.update(('@' + k, v) for k, v in t.attrib.iteritems()) d['text'] = t.text return d