refactor import

This commit is contained in:
Tyrel Souza 2015-09-08 12:43:13 -05:00
parent e47f92d6c8
commit 9f213f3c1f
2 changed files with 24 additions and 19 deletions

View File

@ -33,4 +33,5 @@ class Command(BaseCommand):
gpx = dict(xmltodict.parse(fd.read()))['gpx'] gpx = dict(xmltodict.parse(fd.read()))['gpx']
user = self.user user = self.user
Track.objects.create_from_gpx(gpx, user) created, track = Track.objects.get_or_create_from_gpx(gpx, user)
print track

View File

@ -7,7 +7,7 @@ from django.contrib.auth.models import User
class TrackManager(models.Manager): class TrackManager(models.Manager):
def create_from_gpx(cls, obj, user): def get_or_create_from_gpx(cls, obj, user):
# Get some Meta data from the gpx file. # Get some Meta data from the gpx file.
metadata = obj['metadata'] metadata = obj['metadata']
start_time = metadata['time'] start_time = metadata['time']
@ -15,24 +15,28 @@ class TrackManager(models.Manager):
tracks = obj['trk'] tracks = obj['trk']
name = tracks['name'] name = tracks['name']
segments = tracks['trkseg'] segments = tracks['trkseg']
# Check unimplemented features
with transaction.atomic(): track, created = cls.model.objects.get_or_create(
track = Track.objects.create(user=user, user=user,
start=start_time, start=start_time,
name=name) name=name)
points = segments['trkpt'] if created:
segment = Segment(track=track, time=points[0]['time']) with transaction.atomic():
segment.save() points = segments['trkpt']
for pt in points: segment = Segment(
lat, lon = float(pt['@lat']), float(pt['@lon']) track=track,
poly_pt = geos.Point(lon, lat) time=points[0]['time'])
Point.objects.create(segment=segment, segment.save()
time=pt['time'], for pt in points:
elevation=pt['ele'], lon = float(pt['@lon'])
point=poly_pt) lat = float(pt['@lat'])
return track
raise Exception("Track not created, rolling back DB") Point.objects.create(
segment=segment,
time=pt['time'],
elevation=pt['ele'],
point=geos.Point(lon, lat))
return created, track
class Track(models.Model): class Track(models.Model):