Skip to main content

Loading my Strava Data using Python

I have wanted to load my strava data into my data platform since I started loading the strength data. I found some really useful instructions that I used as by base here.

I basically use the procedures shown to load my last 200 strava activities. I load this into MySQL, find the new entries which then get loaded into the main MySQL table and then a bulk load into Snowflake. My next step will be to process this into a more meaningful table using either dbt or seeing if I can do something smart with python and a view in Snowflake.


# -*- coding: utf-8 -*-
"""
Version Number ||| Mod By ||| Version Date
---------------------------------------------------------
1.00 ||| GM ||| 19 May 2022
"""
from dotenv import load_dotenv
load_dotenv()
import os
from sqlalchemy import create_engine
import requests
import urllib3
import pandas as pd
from snowflake.connector.pandas_tools import pd_writer
import pandasql as ps
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
MySQLHost = os.environ.get("MYSQLHOST")
MySQLUser = os.environ.get("MYSQLSUER")
MySQLPwd = os.environ.get("MYSQLPWD")
MySQLDB = os.environ.get("MYSQLDB")
SnowAcc = os.environ.get("SNOWACC")
SnowUser = os.environ.get("SNOWUSER")
SnowPwd = os.environ.get("SNOWPWD")
SnowDB = os.environ.get("SNOWDB")
SnowWH = os.environ.get("SNOWWH")
SnowSchema = os.environ.get("SNOWSCHEMA")
StravaClient = os.environ.get("STRAVACLIENT")
StravaRefresh = os.environ.get("STRAVAREFRESH")
StravaSecret = os.environ.get("STRAVASECRET")
mySQL_conn = create_engine("mysql+mysqldb://"+MySQLUser+":"+MySQLPwd+'@'+MySQLHost+"/"+MySQLDB);
Snowengine = create_engine(
'snowflake://{user}:{password}@{account}/{db}/{schema}?warehouse={warehouse}'.format(
user= SnowUser,
password= SnowPwd,
account= SnowAcc,
warehouse= SnowWH,
db= SnowDB,
schema=SnowSchema ))
def stravaPipe():
auth_url = "https://www.strava.com/oauth/token"
activites_url = "https://www.strava.com/api/v3/athlete/activities"
payload = {
'client_id': StravaClient,
'client_secret': StravaSecret,
'refresh_token': StravaRefresh,
'grant_type': "refresh_token",
'f': 'json'
}
res = requests.post(auth_url, data=payload, verify=False)
access_token = res.json()['access_token']
header = {'Authorization': 'Bearer ' + access_token}
param = {'per_page': 200, 'page': 1}
my_strava = requests.get(activites_url, headers=header, params=param).json()
normStravaData = pd.json_normalize(my_strava)
normStravaData = normStravaData.drop(['map.summary_polyline','flagged' ,'gear_id' ,'start_latlng' ,'end_latlng'], axis=1)
stravaLimited = ps.sqldf("select name, distance, moving_time, elapsed_time, total_elevation_gain, type, id, start_date_local,average_speed, max_speed, average_cadence, average_heartrate, max_heartrate,elev_high, elev_low, upload_id, upload_id_str FROM normStravaData")
stravaLimited.to_sql('pre_stg_strava', con=mySQL_conn, if_exists='replace',index=False)
## need to add in SQL in here to extract the data from pre stg
stravaDelta = pd.read_sql_query('select * from stg_strava_v',mySQL_conn)
delta = stravaDelta.shape[0]
print(str(delta) + " rows inserted")
stravaDelta.to_sql('stg_strava', con=mySQL_conn, if_exists='append',index=False)
stravaSnow = pd.read_sql_query('select * from stg_strava',mySQL_conn)
stravaSnow.columns = stravaSnow.columns.str.upper()
stravaSnow.to_sql('stg_strava', con=Snowengine, if_exists='replace',index=False, method=pd_writer);
print('Snowflake Load Completed')
view raw stava.py hosted with ❤ by GitHub

Comments

Popular posts from this blog

AWS training cloud academy free course

One of the things I like about this course are the instructors are really clear but also that it provides free labs that allow you to actually sign into AWS and perform some actions to actually create and do things without worrying that you are going to incur a cost.  Today I complete one of the hands on labs.  This was to create a lambda function, in this case it was a very basic python script that was searching a website for a keyword. I then placed this into a schedule and used cloudwatch to create a dashboard that monitored the running of this function. Overall it was a very simple use case but it was also a very simple process to setup.  I don't have much to add to this other than it is well worth signing up to cloud academy for the free training if nothing else, I am tempted, once i have done some more training, to give the paid for option a go to get the full sandboxes. 

AI News

Here’s a concise roundup of the latest AI news from the past couple of days: AI Technology: Friend or Foe? Researchers and experts continue to debate the impact of artificial intelligence. Is it a boon or a threat? The discussion ranges from AI ethics to its potential in various fields. Read more here . 5 Ways Artificial Intelligence Will Change the World by 2050 Futurists predict that AI will revolutionize our lives in the coming decades. From healthcare to transportation, AI is set to transform industries. Explore the possibilities here . How AI Will Transform Businesses in 2023 Business leaders are embracing AI to enhance efficiency, decision-making, and customer experiences. Stay updated on the latest AI trends in the corporate world here . China’s High-Level AI Modules China is pushing the boundaries of AI with modular next-generation systems. These high-level AI technologies promise breakthroughs in fields like robotics, healthcare, and smart cities. Learn more here . The Future ...

Data Cleansing View in Snowflake

For part of one of my free ETLs I am using Zapps to transfer e-mails from Google Sheets and then Keboola to transfer the sheets into my Snowflake database. I am familiar with string searches and cleansing in Oracle and using python but have not had the chance to do this in Snowflake. I wanted to give it a go as a proof of concept if nothing else. There were some difference in functions between Oracle and Snowflake, no INSTR and using POSITION instead and some difference in working with dates / timestamps but overall it was very similar.  The code below is what I ended up using:  I think want to use this to create some overview graphics to allow me to track the success or failure of my ETLs. Assuming the aspects of Retool remain free you can see how much ETL is going on this link .  In case things aren't working, here is a table of the output I am producing.