Add more migrations, import working.

This commit is contained in:
Tyrel Souza 2015-09-01 00:47:56 -04:00
parent aa9c14da6e
commit b94bcf3b02
6 changed files with 117 additions and 28 deletions

View File

@ -1,4 +1,4 @@
Django==1.8.4 Django==1.8.4
django-extensions django-extensions
coverage coverage
gpxpy xmltodict

View File

@ -2,7 +2,8 @@ __author__ = 'tyrel'
from django.core.management.base import BaseCommand, CommandError from django.core.management.base import BaseCommand, CommandError
from django.contrib.auth.models import User from django.contrib.auth.models import User
from tracking.models import Track, Segment, Point from tracking.models import Track, Segment, Point
import gpxpy import xmltodict
import os import os
@ -14,39 +15,58 @@ class Command(BaseCommand):
parser.add_argument('filepath', help="File or directory to import a gpx file.") parser.add_argument('filepath', help="File or directory to import a gpx file.")
def handle(self, *args, **options): def handle(self, *args, **options):
username = options['username'] self.username = options['username']
filepath = options['filepath'] 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) 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): if os.path.isdir(filepath):
self.import_directory(user, filepath) self.import_directory(filepath)
elif os.path.isfile(filepath): elif os.path.isfile(filepath):
self.import_file(user, filepath) self.import_file(filepath)
else: else:
raise CommandError("{0} is neither an existing file, nor a path.".format(filepath)) raise CommandError("{0} is neither an existing file, nor a path.".format(filepath))
def import_directory(self, directory):
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 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):
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()
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): def etree_to_dict(t):

View File

@ -0,0 +1,22 @@
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
from django.conf import settings
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
('tracking', '0002_auto_20150901_0355'),
]
operations = [
migrations.AddField(
model_name='track',
name='user',
field=models.ForeignKey(default=None, to=settings.AUTH_USER_MODEL),
preserve_default=False,
),
]

View File

@ -0,0 +1,19 @@
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('tracking', '0003_track_user'),
]
operations = [
migrations.AddField(
model_name='segment',
name='number',
field=models.IntegerField(default=1),
),
]

View File

@ -0,0 +1,21 @@
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
import datetime
class Migration(migrations.Migration):
dependencies = [
('tracking', '0004_segment_number'),
]
operations = [
migrations.AddField(
model_name='segment',
name='time',
field=models.DateTimeField(default=datetime.datetime(2015, 9, 1, 0, 43, 4, 754000)),
preserve_default=False,
),
]

View File

@ -1,19 +1,26 @@
from django.db import models from django.db import models
# Create your models here. # Create your models here.
from django.contrib.auth.models import User
class Track(models.Model): class Track(models.Model):
user = models.ForeignKey(User, blank=False)
start = models.DateTimeField() start = models.DateTimeField()
name = models.CharField(max_length=1024, blank=False) name = models.CharField(max_length=1024, blank=False)
description = models.TextField(blank=True) description = models.TextField(blank=True)
@property @property
def finish(self): def finish(self):
return self.point_set.order_by("-time")[0].time return self.segment_set.order_by("-time")[0].finish
class Segment(models.Model): class Segment(models.Model):
track = models.ForeignKey(Track) track = models.ForeignKey(Track)
time = models.DateTimeField()
number = models.IntegerField(default=1)
@property
def finish(self):
return self.point_set.order_by("-time")[0].time
class Point(models.Model): class Point(models.Model):
time = models.DateTimeField() time = models.DateTimeField()