Я пытаюсь создать приложение Django с использованием API Spotify и Spotipy. Когда пользователь входит в систему, я хочу создать модели для пользователя, их списки воспроизведения и дорожки в списках воспроизведения.
Я успешно выполнил следующий код:
import sys
import spotipy
import spotipy.util as util
import json
from .models import User, Track, Playlist
#functionality for interacting with the Spotify API through spotipy
class SpotifyServices():
scope = "user-library-read user-read-recently-played"
username = "ratiugo"
token = util.prompt_for_user_token(
username,
scope,
client_id="",
client_secret="",
redirect_uri="http://localhost:8001/radio/home")
spotify = spotipy.Spotify(auth=token)
#create User model and Playlist models for each of the user's playlists, and Track objects for each track connected to a playlist
def create_user_playlist_and_track_models(self):
current_user = User.objects.create(username=self.spotify.current_user()["display_name"])
current_user.save()
# create playlist objects for each playlist
for playlist in self.spotify.current_user_playlists(limit=50)["items"]:
image_url = self.spotify.playlist_cover_image(playlist["id"])[0]["url"]
created_playlist = Playlist.objects.create(
owner=current_user,
name=playlist["name"],
playlist_href=playlist["id"],
image_url=image_url
)
created_playlist.save()
#create Track models for each track in playlist just created
#get playlist track objects
playlist_items = self.spotify.playlist_tracks(playlist["id"])["items"]
#get each track from playlist track object
for item in playlist_items:
#filter 'none' items to prevent crashing
if item["track"] is None:
continue
#if the track object exists, grab the audio features of the track
else:
audio_features = self.spotify.audio_features(item["track"]["id"])
#filter 'none' items to prevent crashing
if audio_features[0] is None:
continue
#if audio features exist, get the 'valence' i.e. mood of the track
else:
valence = audio_features[0]["valence"]
#creation of Track model with relevant data acquired above
new_track = Track.objects.create(
belongs_to_playlist=created_playlist,
title=item["track"]["name"],
artist=item["track"]["artists"][0]["name"],
artistID=item["track"]["artists"][0]["id"],
valence=valence)
new_track.save()
Кому сделать это до 50 плейлистов занимает довольно много времени, но некоторые функции в будущем будут еще хуже, поэтому я решил, что я должен попытаться ускорить его, прежде чем двигаться вперед.
Я читал эту статью , и я пытаюсь реализовать «параллельную версию» параллелизма.
Пока я просто пытаюсь запускать модели плейлистов одновременно, но как только я получу эту работу, я планирую сделать это и для моделей треков.
Пока у меня есть это:
import sys
import spotipy
import spotipy.util as util
import json
from .models import User, Track, Playlist
import concurrent.futures
import threading
#functionality for interacting with the Spotify API through spotipy
class SpotifyServices():
#create a playlist model and corresponding track models
def create_playlist_and_track_model(playlists, self):
scope = "user-library-read user-read-recently-played"
username = "ratiugo"
token = util.prompt_for_user_token(
username,
scope,
client_id="",
client_secret="",
redirect_uri="http://localhost:3000/")
spotify = spotipy.Spotify(
auth=token,
requests_session = True
)
# image_url = spotify.playlist_cover_image(playlist["id"])[0]["url"]
# created_playlist = Playlist.objects.create(
# owner=current_user,
# name=playlist["name"],
# playlist_href=playlist["id"],
# image_url=image_url
# )
# created_playlist.save()
# #create Track models for each track in playlist just created
# #get playlist track objects
# playlist_items = spotify.playlist_tracks(playlist["id"])["items"]
# #get each track from playlist track object
# for item in playlist_items:
# #filter 'none' items to prevent crashing
# if item["track"] is None:
# continue
# #if the track object exists, grab the audio features of the track
# else:
# audio_features = spotify.audio_features(item["track"]["id"])
# #filter 'none' items to prevent crashing
# if audio_features[0] is None:
# continue
# #if audio features exist, get the 'valence' i.e. mood of the track
# else:
# valence = audio_features[0]["valence"]
# #creation of Track model with relevant data acquired above
# new_track = Track.objects.create(
# belongs_to_playlist=created_playlist,
# title=item["track"]["name"],
# artist=item["track"]["artists"][0]["name"],
# artistID=item["track"]["artists"][0]["id"],
# valence=valence)
# new_track.save()
#create User model and Playlist models for each of the user's playlists, and Track objects for each track connected to a playlist
def create_user_playlist_and_track_models(self):
scope = "user-library-read user-read-recently-played"
username = "ratiugo"
token = util.prompt_for_user_token(
username,
scope,
client_id="d679ae3afd4f40268bd9dea2be269276",
client_secret="32c40374e95f4b1b932fdbc4edc02de2",
redirect_uri="http://localhost:3000/")
spotify = spotipy.Spotify(
auth=token,
requests_session = True
)
current_user = User.objects.create(username=spotify.current_user()["display_name"])
current_user.save()
# create playlist objects for each playlist
playlists = spotify.current_user_playlists(limit=10)["items"]
with concurrent.futures.ThreadPoolExecutor(max_workers=10) as executor:
executor.map(self.create_playlist_and_track_model, playlists)
Когда я тестировал его (без комментариев), не было ошибок, и был создан пользователь, но больше ничего не произошло, поэтому Я попытался добавить некоторые заявления для печати. Он напечатает что-нибудь до строки image_url = spotify.playlist_cover_image(playlist["id"])[0]["url"]
, но, похоже, не достигнет ни одного кода после этого. Я новичок в Python, Django и реализую многопоточные программы, поэтому я прошу прощения, если мне не хватает чего-то вопиющего, но я немного растерялся из-за того, как отладить это сейчас.