bikemap/tracking/management/commands/import_gpx.py

37 lines
1.1 KiB
Python
Raw Permalink Normal View History

2015-09-01 03:31:25 +00:00
__author__ = 'tyrel'
from django.core.management.base import BaseCommand, CommandError
from django.contrib.auth.models import User
from tracking.models import Track
2015-09-01 04:47:56 +00:00
import xmltodict
2015-09-01 03:31:25 +00:00
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):
2015-09-01 04:47:56 +00:00
self.username = options['username']
2015-09-01 03:31:25 +00:00
filepath = options['filepath']
2015-09-01 04:47:56 +00:00
2015-09-01 03:31:25 +00:00
try:
2015-09-01 04:47:56 +00:00
self.user = User.objects.get(username=self.username)
2015-09-01 03:31:25 +00:00
except User.DoesNotExist:
2015-09-01 04:47:56 +00:00
raise CommandError("User {0} does not exist".format(self.username))
2015-09-01 03:31:25 +00:00
2015-09-08 16:55:41 +00:00
if os.path.isfile(filepath):
2015-09-01 04:47:56 +00:00
self.import_file(filepath)
2015-09-01 03:31:25 +00:00
else:
raise CommandError("{0} is neither an existing file, nor a path.".format(filepath))
2015-09-01 04:47:56 +00:00
def import_file(self, filename):
with open(filename) as fd:
gpx = dict(xmltodict.parse(fd.read()))['gpx']
2015-09-08 16:55:41 +00:00
user = self.user
2015-09-01 04:47:56 +00:00
2015-09-08 17:43:47 +00:00
Track.objects.get_or_create_from_gpx(gpx, user)