本文介绍了Spotify API 授权 + 令牌密钥错误 - python3的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在使用我的脚本时遇到了这个问题,我有点困惑.过去几周我一直在运行这个脚本,没有出现任何问题,现在我收到了令牌的 KeyError 错误.

I'm running into this issue where with my script and I'm a bit stumped. I've been running this script with no problems for the past few weeks and now I'm getting a KeyError for the token.

这是我的代码:

# IMPORTS
import os
import re
import requests
import json
import numpy as np
import pandas as pd
import time
from pprint import pprint as pp
import datetime as dt
import sys
import spotipy
from spotipy.oauth2 import SpotifyClientCredentials
acc_path = "../../access/"
sys.path.append(acc_path)

pd.set_option('display.max_rows', 10000)
pd.set_option('display.max_columns', 100)
pd.set_option('display.max_colwidth', -1)

# Spotify Credentials
sp_url = 'https://api.spotify.com/v1/'
client_id = os.environ.get('SPOT_CLIENT_ID')
client_secret = os.environ.get('SPOT_CLIENT_SECRET')
output_data = '/users/Desktop/file_date.csv'
spot_scopes = os.environ.get('SPOT_SCOPES')
spot_user_name = os.environ.get('SPOT_USER_NAME') # spotify account username

sp_acc = requests.post('https://accounts.spotify.com/api/token', data = {'grant_type' : 'client_credentials'},
                       auth = (client_id, client_secret))
sp_bear_head = {'Authorization' : 'Bearer' + str(sp_acc.json()['access_token'])}

密钥错误

---> 31 sp_bear_head = {'Authorization' : 'Bearer' + str(sp_acc.json()['access_token'])}

KeyError: 'access_token'

我检查了我的 bash 以确保客户端 ID、秘密范围等都是正确的,并且可以确认这不是问题.这里的任何方向都会非常有帮助!

I checked my bash to make sure client id, secret scopes etc. are all correct and can confirm that is not the issue. Any direction here would be very helpful!

推荐答案

之前有效而现在无效的原因是 access token 过期.

The reason why it worked before and not now is due to the expiration of the access token.

令牌的到期时间由 Spotify 确定,因此您只需解决其设置的限制.

The token's expiration time is determined by Spotify so you just have to work around their set constraints.

话虽如此,您可以根据属性 expires_in 预测何时需要生成/使用新令牌,当您请求令牌时,Spotify 在响应中发回该属性 (https://accounts.spotify.com/api/token).expires_in 属性是一个整数,它告诉您令牌可以使用多少秒.如他们的授权文档所示,expires_in 属性返回值为 3600(秒)或 1 小时.

That being said, you can anticipate when a new token will need to be generated/used based on the property expires_in which Spotify sends back in the response when you request a token (https://accounts.spotify.com/api/token). The expires_in property is an integer and it tells you how many seconds the token will be good for. As seen in their authorization documentation, the expires_in property is returned with the value 3600 (seconds) or, 1 hour.

在那一小时结束后,使用您的refresh_token 请求一个新令牌.

After that hour is up, use your refresh_token to request a new token.

这篇关于Spotify API 授权 + 令牌密钥错误 - python3的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-30 06:11