Skip to content

Commit

Permalink
Merge pull request #49 from enesonus/OVTF-127
Browse files Browse the repository at this point in the history
OVTF-127: Get Average Rating of Song API
  • Loading branch information
enesonus authored Nov 18, 2023
2 parents b6cc76d + df0ef8b commit e0d4e54
Show file tree
Hide file tree
Showing 2 changed files with 41 additions and 3 deletions.
2 changes: 1 addition & 1 deletion apps/songs/urls.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,5 +11,5 @@
path('get-all-genres/', views.get_all_genres, name='get-all-genres'),
path('create-genre/', views.create_genre, name='create-genre'),
path('upload-file/', views.import_song_JSON, name='import-song-json'),

path('get-average-rating/', views.average_song_rating, name='get-average-rating'),
]
42 changes: 40 additions & 2 deletions apps/songs/views.py
Original file line number Diff line number Diff line change
@@ -1,13 +1,13 @@
import json
from datetime import timedelta

from django.db.models import Count, Sum
from django.http import JsonResponse, HttpResponse
from django.shortcuts import render
from django.core.exceptions import ValidationError
from django.views.decorators.csrf import csrf_exempt
import spotipy
from OVTF_Backend.firebase_auth import token_required
from apps.songs.models import Song, Artist, Album, SongArtist, AlbumSong, Genre, GenreSong
from users.models import UserSongRating
from spotipy.oauth2 import SpotifyClientCredentials
import os
import logging
Expand Down Expand Up @@ -288,3 +288,41 @@ def get_all_genres(request):
"genres": list(genres)
}
return JsonResponse(context, status=200)

@csrf_exempt
def average_song_rating(request):
try:
if request.method == 'GET':
data = request.GET
song_id = data.get('song_id')

if song_id is None:
return JsonResponse({'error': 'Missing song id'}, status=400)

try:
song = Song.objects.get(song_id=song_id)
except Song.DoesNotExist:
return JsonResponse({'error': 'Song not found'}, status=404)

try:
rating_aggregation = UserSongRating.objects.filter(song=song).aggregate(
total_ratings=Count('rating'),
sum_ratings=Sum('rating')
)

total_ratings = rating_aggregation['total_ratings']
sum_ratings = rating_aggregation['sum_ratings']

if total_ratings > 0:
average_rating = sum_ratings / total_ratings
return JsonResponse({'average_rating': average_rating}, status=200)
else:
return JsonResponse({'error': 'No ratings available for this song'}, status=404)
except UserSongRating.DoesNotExist:
return JsonResponse({'error': 'No ratings available for this song'}, status=404)
except KeyError as e:
logging.error(f"A KeyError occurred: {str(e)}")
return JsonResponse({'error': 'KeyError occurred'}, status=500)
except Exception as e:
logging.error(f"An unexpected error occurred: {str(e)}")
return JsonResponse({'error': 'An unexpected error occurred'}, status=500)

0 comments on commit e0d4e54

Please sign in to comment.