def download_csv(id=None, date_from=None): # TODO # refresh token logic if expired date_from = int(parse(date_from).timestamp()) authenticated_athlete = Athlete.query.get(id) access_token = authenticated_athlete.access_token client = StravaIO(access_token=access_token) activities = client.get_logged_in_athlete_activities(after=date_from) df_data = defaultdict(list) for activity in activities: for k, v in activity.to_dict().items(): df_data[k].append(v) df = pd.DataFrame(df_data) df.drop(columns=['athlete', 'map'], inplace=True) resp = make_response(df.to_csv()) resp.headers["Content-Disposition"] = "attachment; filename=activities.csv" resp.headers["Content-Type"] = "text/csv" return resp
def stravaAuthentication(request): print('check') auth_res = strava_oauth2(client_id=MY_STRAVA_CLIENT_ID, client_secret=MY_STRAVA_CLIENT_SECRET) client = StravaIO(access_token=auth_res['access_token']) athlete = client.get_logged_in_athlete() athlete = athlete.to_dict() print(athlete) return HttpResponse("Athlete Authenticated: " + athlete['firstname'])
def test_init_stravaio(self): client = StravaIO(access_token='very_secret_token') assert client.configuration.access_token == 'very_secret_token' assert isinstance(client._api_client, swagger_client.ApiClient) assert isinstance(client.athletes_api, swagger_client.AthletesApi) assert isinstance(client.activities_api, swagger_client.ActivitiesApi) assert isinstance(client.streams_api, swagger_client.StreamsApi)
def getIndoorRides(token): indoor = [] client = StravaIO(access_token=token) after = 'Last Month' activityList = client.get_logged_in_athlete_activities(after=after) logging.debug(activityList) for activity in activityList: activity = activity.to_dict() if activity['trainer'] and activity['type'] == 'Ride': ride = { 'strava_link': 'https://www.strava.com/activities/%s' % activity['id'] } indoor.append(ride) return indoor
def get_athlete(access_token=ACCESS_TOKEN): # If the token is stored as an environment variable it is not necessary # to pass it as an input parameters client = StravaIO(access_token=access_token) athlete = client.get_logged_in_athlete() if athlete is None: #You need to authorise the app if you have not done so, #or your access token has expired. oauth2 = strava_oauth2(client_id=CLIENT_ID, client_secret=CLIENT_SECRET_ID) client = StravaIO(access_token=oauth2['access_token']) athlete = client.get_logged_in_athlete() return athlete
def main(): # Check and load .env setup_dotenv() dotenv.load_dotenv() # Get token token = get_token() client = StravaIO(access_token=token['access_token']) # Get the last locally-stored activity last_activity_date = get_most_recent_local_activity() # Get the date seven days prior, in case any activities were uploaded late if last_activity_date is None: date_to_get = None else: date_to_get = last_activity_date - datetime.timedelta(days=7) # Get all activities and write to file activity_dict = get_activities(client, date_to_get) write_activities_to_file(activity_dict)
heatmap_data.append(activity["coordinates"]) flat_list = [item for sublist in heatmap_data for item in sublist] HeatMap( data=flat_list, radius=radius, blur=blur, ).add_to(heatmap_layer) logging.critical("Successfully created heatmap layer.") return heatmap_layer if __name__ == "__main__": refresh_token() client = StravaIO(access_token=os.environ["STRAVA_ACCESS_TOKEN"]) athlete = client.get_logged_in_athlete() activities = client.get_logged_in_athlete_activities(after=20170101) data = download_data(activities=activities, reduce_sample=True) activity_layer = create_activity_layer(activities=data, opacity=0.5, weight=2) heatmap_layer = create_heatmap_layer(data=data, radius=5, blur=5) m = folium.Map( name="Strava Heatmap", tiles="cartodbpositron", location=[59.925, 10.728123], zoom_start=11.5, control_scale=True,
from stravaio import Athlete, StravaIO, Streams, strava_oauth2 from football_strava import SETTINGS resp = strava_oauth2(client_id=SETTINGS.strava_client_id, client_secret=SETTINGS.strava_client_secret) STRAVA_ACCESS_TOKEN = resp["access_token"] client = StravaIO(access_token=STRAVA_ACCESS_TOKEN) athlete: Athlete = client.get_logged_in_athlete() streams: Streams = client.get_activity_streams(4093691464, athlete_id=athlete.id) # Store streams locally (~/.stravadata/streams_<athlete_id>/streams_<id>.parquet) # as a .parquet file, that can be loaded later using gpd.read_parquet() streams.store_locally()
import stravaio def getaccesstoken(): stravaio.strava_oauth2( client_id='61082', client_secret='ba97041b32cb047711da0321c9c85f3aef4db2f4') if __name__ == '__main__': from stravaio import StravaIO # If the token is stored as an environment varible it is not neccessary # to pass it as an input parameters # client = StravaIO(access_token=STRAVA_ACCESS_TOKEN) client = StravaIO() # Get logged in athlete (e.g. the owner of the token) # Returns a stravaio.Athlete object that wraps the # [Strava DetailedAthlete](https://developers.strava.com/docs/reference/#api-models-DetailedAthlete) # with few added data-handling methods athlete = client.get_logged_in_athlete() # Dump athlete into a JSON friendly dict (e.g. all datetimes are converted into iso8601) athlete_dict = athlete.to_dict() # Store athlete infor as a JSON locally (~/.stravadata/athlete_<id>.json) athlete.store_locally() # Get locally stored athletes (returns a generator of dicts) local_athletes = client.local_athletes()
def __init__(self): '''See library for use: https://github.com/sladkovm/stravaio''' creds = settings.PROVIDER_CREDS access_token = creds.get('strava', {}).get('access_token') self.client = StravaIO(access_token=access_token)
from strava_segment_rank.util.strava_api import authenticate from strava_segment_rank.util.strava_api import compute_athlete_segment_frequency import os from stravaio import StravaIO client = StravaIO(access_token=authenticate( os.environ['STRAVA_CLIENT_ID'], os.environ['STRAVA_CLIENT_SECRET'])) def test_compute_athlete_segment_frequency(): print(compute_athlete_segment_frequency(client, 1600211729)) return if __name__ == '__main__': print('Hello World!') test_compute_athlete_segment_frequency()
def strava_segment_rank(start_date, end_date, top_k): """ :param start_date: MM/DD/YYYY :type start_date: str :param end_date: MM/DD/YYYY :type end_date: str :param top_k: top k attempted segments :type top_k: int :return: Pandas DataFrame """ driver = webdriver.Chrome(os.environ['CHROMEDRIVER_PATH']) strava_login( driver, strava_login_url, os.environ['STRAVA_USERNAME'], os.environ['STRAVA_PASSWORD'] ) client = StravaIO( access_token=authenticate( os.environ['STRAVA_CLIENT_ID'], os.environ['STRAVA_CLIENT_SECRET'] ) ) start_date = datetime.datetime( int(start_date.split('/')[2]), int(start_date.split('/')[0]), int(start_date.split('/')[1]), ).timestamp() end_date = datetime.datetime( int(end_date.split('/')[2]), int(end_date.split('/')[0]), int(end_date.split('/')[1]), ).timestamp() segment_frequencies = compute_athlete_segment_frequency(client, int(start_date), int(end_date)) segment_frequencies_df = pandas.DataFrame( { 'segment_id': segment_frequencies.keys(), 'frequency': segment_frequencies.values() } ) segment_leadboard_datas = [] for segment_id, frequency in segment_frequencies.items(): print('Scrapping segment ', str(segment_id)) segment_leaderboard_data = strava_scrape_segment_leaderboard( driver, segment_id, strava_segment_leaderboard_url ) segment_leadboard_datas.append(segment_leaderboard_data) segment_leaderboard_df = pandas.DataFrame(segment_leadboard_datas) final_table = segment_frequencies_df.merge( segment_leaderboard_df, left_on='segment_id', right_on='segment_id' ) driver.close() return final_table
import os import shutil import cv2 import numpy as np import glob output = strava_oauth2(client_id='', client_secret='') # If the token is stored as an environment varible it is not neccessary # to pass it as an input parameters # ## Gathering user routes # In[2]: access_token = str(output["access_token"]) client = StravaIO(access_token=access_token) athlete = client.get_logged_in_athlete().to_dict() athlete_id = athlete["id"] endpoint = "https://www.strava.com/api/v3/athletes/" + str( athlete_id) + "/routes" headers = {"Authorization": "Bearer " + str(access_token)} athlete_routes = requests.get(endpoint, headers=headers).json() route_ids = [] for route in athlete_routes: route_ids.append(route["id"]) print(route_ids)
with open(self.file_name, 'w') as f: yaml.dump(self.settings, f) s = Settings() STRAVA_CLIENT_ID = s.settings['api']['client_id'] STRAVA_CLIENT_SECRET = s.settings['api']['client_secret'] if 'token' not in s.settings or s.settings['token'] is None: data = strava_oauth2(client_id=STRAVA_CLIENT_ID, client_secret=STRAVA_CLIENT_SECRET) s.settings['token'] = data s.save() client = StravaIO(access_token=s.settings['token']['access_token']) athlete = client.get_logged_in_athlete() athlete.store_locally() list_activities = client.get_logged_in_athlete_activities(after='1 september') # Obvious use - store all activities locally for a in list_activities: activity = client.get_activity_by_id(a.id) activity.store_locally() #pprint(activity.to_dict()) line = activity.to_dict()['map']['polyline'] #print(line) points = polyline.decode(line) #pprint(points) if len(points) > 0:
from stravaio import strava_oauth2 from stravaio import StravaIO from config import CLIENT_ID, CLIENT_SECRET from notion_api import NotionInterface token = strava_oauth2(client_id=CLIENT_ID, client_secret=CLIENT_SECRET) # Get Strava Data client = StravaIO(access_token=token["access_token"]) activities = client.get_logged_in_athlete_activities() # Upload information to Notion notion = NotionInterface() table = notion.create_activity_log_table() for activity in activities: notion.add_row_to_table(table, activity)
def test_init_stravaio_env(self): client = StravaIO() access_token = os.getenv('STRAVA_ACCESS_TOKEN', None) assert client.configuration.access_token == access_token
def pullStrava(token, rides, tracksIdx, callLimit): '''pull ride info from strava''' logging.info('Starting to pull ride info from Strava') updatedRides = [] tracks = [] stravaFields = [ 'average_cadence', 'average_speed', 'average_watts', 'calories', 'device_name', 'distance', 'elapsed_time', 'elev_high', 'elev_low', 'gear', 'kilojoules', 'max_speed', 'max_watts', 'moving_time', 'name', 'start_date', 'start_date_local', 'start_latlng', 'trainer', 'timezone', 'total_elevation_gain' ] #TODO -> Want to include gear.name to get bike name client = StravaIO(access_token=token) apiLoopCount = 0 for ride in rides: apiLoopCount += 1 # process activity rideID = ride['strava_link'].rstrip('/').split('/')[-1] logging.info('getting activity: %s' % rideID) logging.info('rideID') logging.info(rideID) logging.info('strava_link') logging.info(ride['strava_link']) activity = client.get_activity_by_id(rideID) activity_dict = activity.to_dict() logging.debug(activity_dict) # store select fields from Strava #ride['strava'] = dict( ((sf, activity_dict[sf] ) for sf in stravaFields) ) strava = {} for sf in stravaFields: logging.debug(sf) try: strava[sf] = activity_dict[sf] except KeyError: logging.debug(sf) pass ride['strava'] = strava logging.debug(ride) try: ride['location'] = ride['strava']['start_latlng'] except KeyError: pass try: ride['strava']['distance_mi'] = round( ride['strava']['distance'] / 1609, 2) except KeyError: print(ride) ride['strava']['distance_mi'] = 0 updatedRides.append(ride) logging.debug(updatedRides) try: if not ride['strava']['trainer']: # Process Streams for ride - Indoor rides don't have gps tracks logging.info('getting stream: %s' % rideID) streams = client.get_activity_streams(id=rideID, athlete_id=None, local=False) streams_dict = streams.to_dict() ride_start = datetime.strptime( activity_dict['start_date'], '%Y-%m-%dT%H:%M:%SZ' ) # I also do this in addWeather, could potentially just do it once for point, value in enumerate(streams_dict['time']): # Create new Track for each point # offset point from start of ride point_dt = ride_start + timedelta( seconds=streams_dict['time'][point]) new_track = { 'strava_link': ride['strava_link'], '_index': tracksIndexName, 'point_ts': point_dt } # Add all stream metrics to new track dict for key in streams_dict.keys(): new_track[key] = streams_dict[key][point] tracks.append(new_track) # Mark the end of the ride tracks[-1]['track_end'] = True except KeyError: pass if apiLoopCount >= callLimit: logging.info( 'Ending Strava API calls early after reaching API CAll Limit (%s)' % callLimit) break logging.info('Finsihed pulling rides from Strava') logging.debug(updatedRides) logging.debug(tracks) return updatedRides, tracks
from stravaio import StravaIO import get_token client = StravaIO(access_token=get_token.token['access_token']) # Store Athlete athlete = client.get_logged_in_athlete() athlete.store_locally() # Generate list of local athletes local_athl_gen = client.local_athletes() local_athl_ids = [] for athl in local_athl_gen: local_athl_ids.append(athl['id']) # Generate list of local activities local_act_ids = [] for athl_id in local_athl_ids: local_acts_gen = client.local_activities(athl_id) for act in local_acts_gen: local_act_ids.append(act['id']) # Store Activities list_activities = client.get_logged_in_athlete_activities(after='last year') for a in list_activities: if a.id not in local_act_ids: client.get_activity_by_id(a.id).store_locally()