Get all pages of playlist data

This also only gets the fields we need
This commit is contained in:
Jake Howard 2022-08-18 09:20:34 +01:00
parent ace30f4dbd
commit 872a6c0b30
Signed by: jake
GPG key ID: 57AFB45680EDD477
2 changed files with 27 additions and 5 deletions

View file

@ -1,6 +1,8 @@
import requests
from django.conf import settings
API_LIMIT = 50
def is_valid_playlist(playlist_id: str) -> bool:
return requests.get(
@ -9,8 +11,28 @@ def is_valid_playlist(playlist_id: str) -> bool:
def get_playlist(playlist_id: str) -> dict:
response = requests.get(
f"https://{settings.SPOTIFY_PROXY_HOST}/v1/playlists/{playlist_id}"
playlist_response = requests.get(
f"https://{settings.SPOTIFY_PROXY_HOST}/v1/playlists/{playlist_id}",
params={"fields": "name,external_urls.spotify,tracks.total"},
)
response.raise_for_status()
return response.json()
playlist_response.raise_for_status()
playlist_data = playlist_response.json()
tracks = []
for offset in range(0, playlist_data["tracks"]["total"], API_LIMIT):
tracks_response = requests.get(
f"https://{settings.SPOTIFY_PROXY_HOST}/v1/playlists/{playlist_id}/tracks",
params={
"offset": str(offset),
"limit": str(API_LIMIT),
"fields": "items(track(name,album.name,album.images,artists.name,external_urls.spotify,preview_url))",
},
)
tracks_response.raise_for_status()
tracks.extend(tracks_response.json()["items"])
playlist_data["tracks"] = sorted(
tracks, key=lambda track: track["track"]["name"].lower()
)
return playlist_data

View file

@ -14,7 +14,7 @@
</tr>
</thead>
<tbody>
{% include "spotify/spotify-items.html" with tracks=playlist.tracks.items %}
{% include "spotify/spotify-items.html" with tracks=playlist.tracks %}
</tbody>
</table>
</section>