I'm a self-taught Python programmer and I never really learned the fundamentals of programming, so I want to see how to improve upon this script and make it adhere to best practices.
The script has three functions that retrieve data from an API, cleanse the data and store it in a sqlite db. This script is going to run daily on a cron and append to the sqlite tables every morning.
get_data()
fetches the data and turns it into a pandas dataframe.data_cleanse()
removes some non-necessary data.send_to_db()
sends the cleansed data to a sqlite db, there is one table for each of the event types.
All of the functions are called in a for
-loop which iterates through each of the event types.
I'm open to any suggestions on how to improve this, but here are some thoughts/questions that I have:
Should this be a class? I have never used one before because I always found plain functions to be less confusing.
Should I be using a
if __name__ == "__main__":
?
import pandas as pd
import json
from datetime import date, timedelta
from mixpanel_client_lib import Mixpanel
import sqlite3 as db
def get_data(start_date, end_date, event_name):
con_data = Mixpanel(API_KEY, API_SECRET)
data = con_data.request(['export'], {
'event': [event_name],
'from_date': start_date,
'to_date': end_date
})
parameters = set()
events = []
for line in data.split('\n'):
try:
event = json.loads(line)
ev = event['properties']
except ValueError:
continue
parameters.update(ev.keys())
events.append(ev)
df = pd.DataFrame(events)
return df, event_name
def data_cleanse(df, event_name):
if event_name == "Video Played":
df = df[['$ios_ifa',
'Groups',
'Lifetime Number of Sessions',
'Days Since Last Visit',
'time',
'Product ID',
'Time Watched',
'Video Length']]
df.columns = ['ios_id',
'groups',
'lifetime_sessions',
'days_since',
'time',
'product_id',
'time_watched',
'video_length']
print df['lifetime_sessions'].value_counts()
df['groups'] = df['groups'].astype(str)
# remove admin users from data
idx = df['groups'].isin(['[u\'Admin-Personal\']', '[u\'Admin\']'])
df = df[~idx]
# remove '0' lifetime session users from data
idx = df['lifetime_sessions'].isin([0])
df = df[~idx]
return df, event_name
elif event_name == "Item Information Click" or 'Faved' or 'Add to Cart' or 'Tap to Replay':
print df.columns.values
df = df[['$ios_ifa',
'Groups',
'Lifetime Number of Sessions',
'Days Since Last Visit',
'time',
'Product ID']]
df.columns = ['ios_id',
'groups',
'lifetime_sessions',
'days_since',
'time',
'product_id']
df['groups'] = df['groups'].astype(str)
# remove admin users from data
idx = df['groups'].isin(['[u\'Admin-Personal\']', '[u\'Admin\']'])
df = df[~idx]
# remove '0' lifetime session users from data
idx = df['lifetime_sessions'].isin([0])
df = df[~idx]
return df, event_name
def send_to_db(df, event_name):
table_names = {
'Video Played': 'video_played',
'Item Information Click': 'item_info_click',
'Faved': 'faved',
'Add to Cart': 'add_to_cart',
'Tap to Replay': 'replay'
}
con = db.connect('/code/vid_score/test.db')
df.to_sql(table_names.get(event_name), con, flavor='sqlite', if_exists='append')
con.close()
################
API_KEY = 'xxxxxxx'
API_SECRET = 'xxxxxxx'
event_types = ['Video Played',
'Item Information Click',
'Faved',
'Add to Cart',
'Tap to Replay']
end_date = date.today() - timedelta(1)
start_date = date.today() - timedelta(1)
for event in event_types:
df, event_name = get_data(start_date, end_date, event)
df, event_name = data_cleanse(df, event_name)
send_to_db(df, event_name)