Browse Source

Retrieve audio feature data from frontend

Added user_secret field to User. Set up a basic JavaScript function for
querying audio feature data from the frontend.
master
Chris Shyi 7 years ago
parent
commit
3e35e52f45
  1. 2
      .gitignore
  2. 2
      spotifyvis/models.py
  3. 28
      spotifyvis/static/spotifyvis/scripts/user_data.js
  4. 11
      spotifyvis/templates/spotifyvis/user_data.html
  5. 2
      spotifyvis/urls.py
  6. 31
      spotifyvis/views.py

2
.gitignore

@ -3,7 +3,7 @@ db.sqlite3
*.bak
.idea/
.vscode/*
spotifyvis/migrations/*
api-keys.sh
Pipfile
*.txt

2
spotifyvis/models.py

@ -28,7 +28,7 @@ class User(models.Model):
verbose_name_plural = "Users"
user_id = models.CharField(primary_key=True, max_length=MAX_ID) # the user's Spotify ID
# username = models.CharField(max_length=30) # User's Spotify user name, if set
user_secret = models.CharField(max_length=30, default='')
def __str__(self):
return self.user_id

28
spotifyvis/static/spotifyvis/scripts/user_data.js

@ -0,0 +1,28 @@
/**
* Retrieves data for a specific audio feature for a certain user
* @param audioFeature: the audio feature for which data will be retrieved
* @param clientSecret: the client secret, needed for security
*/
function getAudioFeatureData(audioFeature, userSecret) {
let httpRequest = new XMLHttpRequest();
/*
* Handler for the response
*/
httpRequest.onreadystatechange = function() {
if (httpRequest.readyState === XMLHttpRequest.DONE) {
if (httpRequest.status === 200) {
let responseData = JSON.parse(httpRequest.responseText);
// TODO: The data points need to be plotted instead
for (let data of responseData.data_points) {
console.log(data);
}
} else {
alert("There was a problem with the login request, please try again!");
}
}
};
let queryString = `/audio_features/${audioFeature}/${userSecret}`;
httpRequest.open('GET', queryString, true);
httpRequest.send();
}

11
spotifyvis/templates/spotifyvis/user_data.html

@ -16,11 +16,10 @@
<p class="browsehappy">You are using an <strong>outdated</strong> browser. Please <a href="#">upgrade your browser</a> to improve your experience.</p>
<![endif]-->
<p>Logged in as {{ id }}</p>
<h2>Display name {{ user_name }}</h2>
<ul>
{% for genre_name, genre_count in genre_dict.items %}
<li>{{ genre_name }} - {{ genre_count }}</li>
{% endfor %}
</ul>
<script src="{% static "spotifyvis/scripts/user_data.js" %}"></script>
<script>
sessionStorage.setItem('user_secret', "{{ user_secret }}");
getAudioFeatureData('instrumentalness', sessionStorage.getItem('user_secret'));
</script>
</body>
</html>

2
spotifyvis/urls.py

@ -10,4 +10,6 @@ urlpatterns = [
path('user_data', user_data, name='user_data'),
path('test_db', test_db, name='test_db'),
path('user_artists/<str:user_id>', get_artist_data, name='get_artist_data'),
path('audio_features/<str:audio_feature>/<str:client_secret>', get_audio_feature_data, name='get_audio_feature_data'),
]

31
spotifyvis/views.py

@ -105,7 +105,7 @@ def callback(request):
'client_secret': os.environ['SPOTIFY_CLIENT_SECRET'],
}
response = requests.post('https://accounts.spotify.com/api/token', data = payload).json()
response = requests.post('https://accounts.spotify.com/api/token', data=payload).json()
# despite its name, datetime.today() returns a datetime object, not a date object
# use datetime.strptime() to get a datetime object from a string
request.session['token_obtained_at'] = datetime.strftime(datetime.today(), TIME_FORMAT)
@ -145,12 +145,15 @@ def user_data(request):
request.session['user_id'] = user_data_response['id'] # store the user_id so it may be used to create model
# request.session['user_name'] = user_data_response['display_name']
# get_or_create() returns a tuple (obj, created)
user = User.objects.get_or_create(user_id=user_data_response['id'])[0]
try:
user = User.objects.get(user_id=user_data_response['id'])
except User.DoesNotExist:
user = User(user_id=user_data_response['id'], user_secret=generate_random_string(30))
user.save()
context = {
'user_name': user_data_response['display_name'],
'id': user_data_response['id'],
'user_secret': user.user_secret,
}
parse_library(headers, TRACKS_TO_QUERY, user)
@ -178,3 +181,23 @@ def get_artist_data(request, user_id):
processed_artist_data = [{'name': artist.name, 'num_songs': artist.num_songs} for artist in artist_counts]
return JsonResponse(data=processed_artist_data, safe=False)
def get_audio_feature_data(request, audio_feature, client_secret):
"""Returns all data points for a given audio feature
Args:
request: the HTTP request
audio_feature: The audio feature to be queried
client_secret: client secret, used to identify the user
"""
user = User.objects.get(user_secret=client_secret)
user_tracks = Track.objects.filter(users=user)
response_payload = {
'data_points': [],
}
for track in user_tracks:
audio_feature_obj = AudioFeatures.objects.get(track=track)
response_payload['data_points'].append(getattr(audio_feature_obj, audio_feature))
return JsonResponse(response_payload)
Loading…
Cancel
Save