Wrote parse_library and get_track_info (#1)
Initialized library_stats with top-level keys and default values.
This commit is contained in:
@@ -5,9 +5,14 @@ import random
|
||||
import requests
|
||||
import os
|
||||
import urllib
|
||||
import json
|
||||
import pprint
|
||||
from datetime import datetime
|
||||
|
||||
TIME_FORMAT = '%Y-%m-%d-%H-%M-%S'
|
||||
library_stats = {"audio_features":{}, "genres":{}, "year_released":{}, "artists":{}, "num_songs":0, "popularity":[], "total_runtime":0}
|
||||
|
||||
# generate_random_string {{{ #
|
||||
|
||||
def generate_random_string(length):
|
||||
"""Generates a random string of a certain length
|
||||
@@ -26,6 +31,9 @@ def generate_random_string(length):
|
||||
|
||||
return rand_str
|
||||
|
||||
# }}} generate_random_string #
|
||||
|
||||
# token_expired {{{ #
|
||||
|
||||
def token_expired(token_obtained_at, valid_for):
|
||||
"""Returns True if token expired, False if otherwise
|
||||
@@ -37,11 +45,17 @@ def token_expired(token_obtained_at, valid_for):
|
||||
time_elapsed = (datetime.today() - token_obtained_at).total_seconds()
|
||||
return time_elapsed >= valid_for
|
||||
|
||||
# }}} token_expired #
|
||||
|
||||
# index {{{ #
|
||||
|
||||
# Create your views here.
|
||||
def index(request):
|
||||
return render(request, 'spotifyvis/index.html')
|
||||
|
||||
# }}} index #
|
||||
|
||||
# login {{{ #
|
||||
|
||||
def login(request):
|
||||
|
||||
@@ -62,6 +76,10 @@ def login(request):
|
||||
authorize_url = "https://accounts.spotify.com/authorize/?{}".format(params)
|
||||
return redirect(authorize_url)
|
||||
|
||||
# }}} login #
|
||||
|
||||
# callback {{{ #
|
||||
|
||||
def callback(request):
|
||||
# Attempt to retrieve the authorization code from the query string
|
||||
try:
|
||||
@@ -88,6 +106,9 @@ def callback(request):
|
||||
|
||||
return redirect('user_data')
|
||||
|
||||
# }}} callback #
|
||||
|
||||
# user_data {{{ #
|
||||
|
||||
def user_data(request):
|
||||
|
||||
@@ -116,4 +137,81 @@ def user_data(request):
|
||||
'user_name': user_data_response['display_name'],
|
||||
'id': user_data_response['id'],
|
||||
}
|
||||
return render(request, 'spotifyvis/user_data.html', context)
|
||||
|
||||
parse_library(headers, 4)
|
||||
return render(request, 'spotifyvis/user_data.html', context)
|
||||
|
||||
# }}} user_data #
|
||||
|
||||
# parse_library {{{ #
|
||||
|
||||
def parse_library(headers, tracks):
|
||||
"""Scans user's library for certain number of tracks to update library_stats with.
|
||||
|
||||
:headers: For API call.
|
||||
:tracks: Number of tracks to get from user's library.
|
||||
:returns: None
|
||||
|
||||
"""
|
||||
# TODO: implement importing entire library with 0 as tracks param
|
||||
# number of tracks to get with each call
|
||||
limit = 2
|
||||
# keeps track of point to get songs from
|
||||
offset = 0
|
||||
payload = {'limit': str(limit)}
|
||||
for i in range(0, tracks, limit):
|
||||
payload['offset'] = str(offset)
|
||||
saved_tracks_response = requests.get('https://api.spotify.com/v1/me/tracks', headers=headers, params=payload).json()
|
||||
for track_dict in saved_tracks_response['items']:
|
||||
get_track_info(track_dict['track'])
|
||||
# calculates num_songs with offset + songs retrieved
|
||||
library_stats['num_songs'] = offset + len(saved_tracks_response['items'])
|
||||
offset += limit
|
||||
|
||||
pprint.pprint(library_stats)
|
||||
|
||||
# }}} parse_library #
|
||||
|
||||
# increase_nested_key {{{ #
|
||||
|
||||
def increase_nested_key(top_key, nested_key):
|
||||
"""Increases count for the value of library_stats[top_key][nested_key]. Checks if nested_key exists already and takes
|
||||
appropriate action.
|
||||
|
||||
:top_key: First key of library_stats.
|
||||
:nested_key: Key in top_key's dict for which we want to increase value of.
|
||||
:returns: None
|
||||
|
||||
"""
|
||||
if nested_key not in library_stats[top_key]:
|
||||
library_stats[top_key][nested_key] = 1
|
||||
else:
|
||||
library_stats[top_key][nested_key] += 1
|
||||
|
||||
# }}} increase_nested_key #
|
||||
|
||||
# get_track_info {{{ #
|
||||
|
||||
def get_track_info(track_dict):
|
||||
"""Get all the info from the track_dict directly returned by the API call in parse_library.
|
||||
|
||||
:track_dict: Dict returned from the API call containing the track info.
|
||||
:returns: None
|
||||
|
||||
"""
|
||||
# popularity
|
||||
library_stats['popularity'].append(track_dict['popularity'])
|
||||
|
||||
# year
|
||||
year_released = track_dict['album']['release_date'].split('-')[0]
|
||||
increase_nested_key('year_released', year_released)
|
||||
|
||||
# artist
|
||||
artist_names = [artist['name'] for artist in track_dict['artists']]
|
||||
for artist_name in artist_names:
|
||||
increase_nested_key('artists', artist_name)
|
||||
|
||||
# runtime
|
||||
library_stats['total_runtime'] += float(track_dict['duration_ms']) / 60
|
||||
|
||||
# }}} get_track_info #
|
||||
|
||||
Reference in New Issue
Block a user