问题
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.
Here's my code:
# 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'])}
KeyERROR
---> 31 sp_bear_head = {'Authorization' : 'Bearer' + str(sp_acc.json()['access_token'])}
KeyError: 'access_token'
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!
回答1:
The reason why it worked before and not now is due to the expiration of the access token
.
The token's expiration time is determined by Spotify so you just have to work around their set constraints.
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.
After that hour is up, use your refresh_token
to request a new token.
来源:https://stackoverflow.com/questions/60980531/spotify-api-authorization-token-key-error-python3