为什么我一直得到一个400坏请求错误时,从Spotify API交换访问令牌的代码?


import requests
import base64
from secrets import USER_CLIENT_ID, USER_CLIENT_SECRET, USER_REDIRECT_URI
# using OAuth we create a link to redirect user to their spotify account
def create_oauth_link():
params = {
"client_id": USER_CLIENT_ID,
"response_type": "code",
"redirect_uri": USER_REDIRECT_URI,
"scope": "user-read-private user-read-email"
}
endpoint = "https://accounts.spotify.com/authorize"
response = requests.get(endpoint, params=params)
url = response.url
return url
# authorization process to exchange code for token
def exchange_code_token(code=None):
message = f"{USER_CLIENT_ID}:{USER_CLIENT_SECRET}"
messageBytes = message.encode("ascii")
base64Bytes = base64.b64encode(messageBytes)
base64Message = base64Bytes.decode("ascii")
headers = {'Authorization': f'Basic {base64Message}'}
params = {
'grant_type': "authorization_code",
"code": code,
"redirect_uri": USER_REDIRECT_URI,
#"client_id": USER_CLIENT_ID,
#"client_secret": USER_CLIENT_SECRET,
}
endpoint = "https://accounts.spotify.com/api/token"
response = requests.post(endpoint, params=params, headers=headers)
print(response.reason)
link = create_oauth_link()
print(f"Follow the link to start the authentication with Spotify: {link}")
code = input("Spotify Code: ")
exchange_code_token(code)

我正在成功地生成代码,但在试图将其交换为访问令牌时一切都出错了。我得到了一个糟糕的请求响应。我试过通过请求参数通过Spotify的文档以及base64编码传递client_id和client_secret,但似乎没有任何作用。有什么问题吗?

不是client_id和client_secret通常不一起在一个OAuth请求?此外,有时你需要一个本地token.txt,它将在你手动登录一个网站请求后创建。. txt。包含一个额外的访问令牌!这似乎就是你的问题所在。此代码应该将您重定向到spotify页面(如果您在spotify中创建了应用程序),并且应该要求您采取行动(点击按钮或类似的东西)而不是您的token.txt。将在您的文件夹中创建。如果没有,请自己创建。

这是我曾经用spotify写过的东西,用来创建我自己的前100名音乐列表,这些列表是从一个网站上刮下来的,然后在spotify上搜索。请复制OAuth策略:

import spotipy
from spotipy.oauth2 import SpotifyOAuth
import requests
from bs4 import BeautifulSoup
client_id = "your id"
client_secret = "your secret"
time_travel = input("Which year you want to travel to? Insert a format of YYYY-MM-DD: ")
response = requests.get(url=f"https://www.billboard.com/charts/hot-100/{time_travel}")
time_travel = time_travel.split("-")[0]
soup = BeautifulSoup(response.text, "lxml")
interpret = soup.find_all(name="span",
class_="chart-element__information__artist text--truncate color--secondary")
title = soup.find_all(name="span",
class_="chart-element__information__song text--truncate color--primary")
top_100_interpret = [element.string for element in interpret]
top_100_title = [element.string for element in title]
sp = spotipy.Spotify(
auth_manager=SpotifyOAuth(
scope="playlist-modify-private playlist-modify-public",
redirect_uri="http://localhost:8888/callback",
client_id=client_id,
client_secret=client_secret,
show_dialog=True,
cache_path="token.txt")
)
uris_artists = []
found_spotify_tracks = []
#search artist
#for artist in top_100_interpret[:10]:
for artist in top_100_interpret:
try:
result = sp.search(q=f"artist:{artist} year:{time_travel}", type="artist")
uri_artist = result["artists"]["items"][0]["uri"]
#search top ten 10 of artist
tracks = [sp.artist_top_tracks(uri_artist, country="US")["tracks"][_]["name"] for _ in range(10)]
tracks_uri = [sp.artist_top_tracks(uri_artist, country="US")["tracks"][_]["uri"] for _ in range(10)]
found_track = [track in top_100_title for track in tracks]
index_found_spotify = found_track.index(True)
except:
uri_artist = ""
tracks = ""
print("Artist or Song not found")
else:
found_spotify_tracks.append(tracks_uri[index_found_spotify])

def create_playlist() -> str:
playlist_name = f"Top 100 in {time_travel}"
user_id = sp.current_user()["id"]
playlist_dict = sp.user_playlist_create(user_id,
playlist_name,
public=True,
collaborative=False,
description='Auto generated Playlist with Python, if track found')
return playlist_dict

def add_to_playlist(id_name: str, uris: list) -> None:
sp.playlist_add_items(id_name, uris, position=None)

playlist_dict = create_playlist()
add_to_playlist(playlist_dict["uri"], found_spotify_tracks)

相关内容

最新更新