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


from gear.mixins import StravaGearMixin

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

        self.activity_type = self.activity_type =
        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 = \
        self.start_date = act.start_date
        self.timezone =

        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)
        return self


class Gear(DistanceModel, TimeStampedModel):
    def update_with_strava(self, gear):
        self.external_id = =
        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

        return self


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)


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)


        return gear
comments powered by Disqus