我正在使用Spotify API包装器提取数据。访问令牌(这是全局变量)仅有效1小时,因此我需要在某些定义函数的for循环期间对其进行更新。我尝试使用try / except更新它,但出现以下错误:
UnboundLocalError:分配前已引用局部变量“ spotify”。
以下是相关代码:
token = credentials.get_access_token()
spotify = spotipy.Spotify(auth = token)
...
def main():
...
df_af = generate_audio_features_df(track_ids)
...
def generate_audio_features_df(track_ids):
col_list = ['id', 'danceability']
result = []
count = 0
for j in track_ids:
try:
r = spotify.audio_features(j)[0]
features_list = [r['id'], r['danceability']]
result.append(features_list)
#display progress
count += 1
print("Added ", count, " track")
except spotipy.client.SpotifyException:
token = credentials.get_access_token()
spotify = spotipy.Spotify(auth = token)
df = pd.DataFrame(data = result, columns = col_list)
return df
if __name__ == "__init__":
main()
我希望代码更新令牌并返回循环。