bikemap/tracking/management/commands/import_gpx.py
2015-09-08 12:43:47 -05:00

37 lines
1.1 KiB
Python

__author__ = 'tyrel'
from django.core.management.base import BaseCommand, CommandError
from django.contrib.auth.models import User
from tracking.models import Track
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.isfile(filepath):
self.import_file(filepath)
else:
raise CommandError("{0} is neither an existing file, nor a path.".format(filepath))
def import_file(self, filename):
with open(filename) as fd:
gpx = dict(xmltodict.parse(fd.read()))['gpx']
user = self.user
Track.objects.get_or_create_from_gpx(gpx, user)