Saving Data from Strava

Getting data can be easy. Effectively saving it from one source to your database can be a pain. In this video we explore a way to get data from Strava and save it to our database with as little future trouble as possible.

resources Strava's v3 API stravalib

activities/models.py

from gear.mixins import StravaGearMixin


class Activity(StravaGearMixin, DistanceModel, TimeStampedModel):
    def update_with_strava(self, act):
        self.external_id = act.id
        self.distance = act.distance.get_num()
        self.distance_unit = act.distance.get_unit().specifier

        self.activity_type = self.activity_type

        self.name = act.name
        self.moving_time = act.moving_time.total_seconds()
        self.elapsed_time = act.elapsed_time.total_seconds()
        self.total_elevation_gain = act.total_elevation_gain
        self.total_elevation_gain_unit = \
            act.total_elevation_gain.get_unit().specifier
        self.start_date = act.start_date
        self.timezone = act.timezone.zone

        self.location_city = act.location_city
        self.location_state = act.location_state
        self.location_country = act.location_country

        self.trainer = act.trainer
        self.commute = act.commute
        self.manual = act.manual
        self.private = act.private
        self.flagged = act.flagged

        if act.gear_id:
            self.gear = self.get_strava_gear(self, act.gear_id)

        self.save()
        return self

gear/models.py

class Gear(DistanceModel, TimeStampedModel):
    def update_with_strava(self, gear):
        self.external_id = gear.id
        self.name = gear.name
        self.distance = gear.distance
        self.distance_unit = gear.distance.get_unit().specifier
        self.primary = gear.primary
        self.brand_name = gear.brand_name
        self.model_name = gear.model_name
        self.description = gear.description

        self.save()

        return self

core/mixins.py

from stravalib.client import Client

class StravaClientMixin(object):
    def get_strava_client(self, user):
        strava = user.social_auth.get()
        return Client(access_token=strava.tokens)

gear/mixins.py

from core.mixins import StravaClientMixin

class StravaGearMixin(StravaClientMixin):
    def get_strava_gear(self, activity, gear_id=None):
        from .models import Gear
        gear, created = Gear.objects.get_or_create(
            user=activity.user, external_id=gear_id)

        if created:
            client = self.get_strava_client(activity.user)
            strava_gear = client.get_gear(gear_id)

            gear.update_with_strava(strava_gear)

        return gear
comments powered by Disqus