bikemap/tracking/management/commands/import_gpx.py

56 lines
1.7 KiB
Python

__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 gpxpy
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):
username = options['username']
filepath = options['filepath']
try:
user = User.objects.get(username=username)
except User.DoesNotExist:
raise CommandError("User %s does not exist" % username)
self.stdout.write("Importing for user %s" % user.username)
if os.path.isdir(filepath):
self.import_directory(user, filepath)
elif os.path.isfile(filepath):
self.import_file(user, filepath)
else:
raise CommandError("{0} is neither an existing file, nor a path.".format(filepath))
def import_file(self, user, filename):
with open(filename, 'r') as f:
gpx = gpxpy.parse(f)
for g_track in gpx.tracks:
for g_segment in g_track.segments:
for g_point in g_segment.points:
print 'Point at ({0},{1}) -> {2} -> {3}'.format(g_point.latitude, g_point.longitude, g_point.elevation)
def import_directory(self, user, directory):
pass
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