Spotify API 的 Python 脚本令牌刷新机制问题

问题描述 投票:0回答:0

我正在编写一个 python 脚本,使用 spotify api 遍历新的音乐编辑播放列表,将曲目、艺术家、专辑信息拉入 csv 文件。我的脚本在一段时间内运行良好,完美地执行了我的 id 列表中播放列表中的所有曲目,但在大约一个小时的运行时间后处理曲目时停止了。我认为这可能与我的访问令牌过期有关,所以我在脚本的开头添加了一些代码以获取缓存的访问令牌信息并在每次新运行时刷新它,认为这将重新启动至少一个新的运行时间-time 这样我就可以更深入地了解是否/在何处需要添加自动刷新,而如果我的访问令牌在未来到期,则在迭代数据拉动时。无论出于何种原因,我的脚本都没有向控制台检索错误请求或令牌过期错误,它只是在处理第一个播放列表中的第一首曲目时卡住了,如下面的屏幕截图所示。对于上下文,当它工作时,控制台正在以相同格式打印我列表中所有播放列表 ID 中的每条曲目,然后它像现在一样卡在单个播放列表的中间,但现在它卡在了最中间第一个播放列表中的第一首曲目。我几乎可以肯定这是我的访问令牌的某种问题,我想我的问题是为什么它会卡住而不抛出错误,我该如何解决这个问题以便它自动正确刷新以继续运行而不提前退出执行。谢谢!

[![当前输出,卡住处理第一轨道如上所述。之前,正在运行许多曲目并正确迭代播放列表,直到在这里同样卡住,现在只做 1 首曲目。][1]][1]


import csv
from datetime import datetime, timedelta
import spotipy
from spotipy.oauth2 import SpotifyOAuth
import time

# Set up credentials and authorization parameters
client_id = 'myclientid'
client_secret = 'myclientsecret'
redirect_uri = 'https://google.com/'
scope = 'playlist-modify-public playlist-modify-private'
username = 'myusername'

# Create Spotipy object using SpotifyOAuth
sp = spotipy.Spotify(
    auth_manager=SpotifyOAuth(
        client_id=client_id,
        client_secret=client_secret,
        redirect_uri=redirect_uri,
        scope=scope,
        username=username
    )
)

# Refresh access token **This is what I added after realizing program was getting stuck after about an hour of run-time**

token_info = sp.auth_manager.get_cached_token()
sp.auth_manager.refresh_access_token(token_info['refresh_token'])
print("Refreshing Access Token.")
new_token_info = sp.auth_manager.get_cached_token()
print("Old access token:", token_info['access_token'])
print("New access token:", new_token_info['access_token'])

# Define a list of playlist IDs
playlist_ids = ['37i9dQZF1DX4JAvHpjipBk', '37i9dQZF1DX0XUsuxWHRQd', '37i9dQZF1DXdwmD5Q7Gxah', ...]

tracksData = []

# Iterate through playlist IDs and extract track information
for playlist_id in playlist_ids:
    # Use Spotipy API to get playlist data
    playlist = sp.playlist(playlist_id)

    # Use Spotipy API to get track data
    results = sp.playlist_tracks(playlist_id)

    count = 1

    # Extract track information and add to tracksData array
    for track in results['items']:
        track = track['track']
        print(f"Processing track: {track['artists'][0]['name']} - {track['name']} from playlist: {playlist['name']}")
        start_time = time.time()
        try:
            sp.artist(track['artists'][0]['id'])
            sp.track(track['id'])
            sp.album(track['album']['id'])
        except:
            pass
        elapsed_time = time.time() - start_time
        if elapsed_time > 3:
            print(f"Skipping track: {track['artists'][0]['name']} - {track['name']} from playlist: {playlist['name']} (took too long to process)")
            continue
        tracksData.append({
            'artistName': track['artists'][0]['name'],
            'songName': track['name'],
            'releaseDate': track['album']['release_date'],
            'positionInPlaylist': count,
            'artistFollowers': sp.artist(track['artists'][0]['id'])['followers']['total'],
            'albumImageUrl': track['album']['images'][0]['url'],
            'trackPopularity': track['popularity'],
            'artistPopularity': sp.artist(track['artists'][0]['id'])['popularity'],
            'isrc': track['external_ids']['isrc'],
            'albumLabel': sp.album(track["album"]["id"])["label"],
            'albumExternalUrl': track['album']['external_urls']['spotify'],
            'playlistId': playlist_id,
            'playlistName': playlist['name'], # Set playlistName to actual name of playlist
            'playlistImage': playlist['images'][0]['url'], # Add playlist image to dictionary
            'playlistFollowers': playlist['followers']['total'], # Add playlist followers to dictionary
            'trackId': track['id'], # Add track ID to dictionary
            'albumId': track['album']['id'] # Add album ID to dictionary
        })
        count += 1

    time.sleep(2) # Pause for 2 seconds before processing the next playlist

# Calculate the most recent Friday
today = datetime.today()
friday = today - timedelta((today.weekday() - 4) % 7)

# Calculate the date 7 days prior to the most recent Friday
lastWeekFriday = friday - timedelta(days=7)

# Create a list of track dictionaries with release dates within the past week
recentTracks = []

for track in tracksData:
    # Convert release date string to datetime object
    releaseDate = datetime.strptime(track['releaseDate'], '%Y-%m-%d')

    # Check if release date is within the past week
    if lastWeekFriday <= releaseDate < friday:
        recentTracks.append(track)

# Create and write track data to CSV file
with open('tracksData.csv', mode='w', newline='') as csv_file:
    fieldnames = ['artistName', 'songName', 'releaseDate', 'positionInPlaylist', 'artistFollowers', 'albumImageUrl',
                  'trackPopularity', 'artistPopularity', 'isrc', 'albumLabel', 'albumExternalUrl', 'playlistId',
                  'playlistName', 'playlistImage', 'playlistFollowers', 'trackId', 'albumId']
    writer = csv.DictWriter(csv_file, fieldnames=fieldnames)

    writer.writeheader()
    for track in recentTracks:
        writer.writerow(track)


  [1]: https://i.stack.imgur.com/AJFR2.png
python api oauth access-token spotify
© www.soinside.com 2019 - 2024. All rights reserved.