Spotify API - 状态:403,代码:-1 - 客户端范围不足,原因:无

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

每次我运行以下代码时,它都会给我同样的错误,但是它在 5 分钟前工作,所改变的是我去洗手间,然后回来更改变量名称

username = '9qk7akrruah30sd2qix0x4lmp'
client_id = 'c97fbdbd18674cf3851def089d654a65'
client_secret = '{My Client Secret}'
redirect_uri = 'http://localhost:80'

# Set up Spotify API client with client ID, secret, and redirect URI
sp = spotipy.Spotify(auth_manager=SpotifyOAuth(
    client_id=client_id,
    client_secret=client_secret,
    redirect_uri=redirect_uri,
    scope="user-library-read"  # Add the required scopes here
))

# Get the access token
access_token_info = sp.auth_manager.get_access_token(as_dict=False)

# Print the access token
print(access_token_info)

def create_playlist_with_recommendations(type, id, playlist_name='Recommendeded Playlist'):
    sp = spotipy.Spotify(auth=access_token_info, auth_manager=SpotifyOAuth(client_id=client_id,
                                                                      client_secret=client_secret,
                                                                      redirect_uri=redirect_uri,
                                                                      scope='playlist-modify-public'))

    # Get similar tracks
    # Get similar tracks
    if type == "track":
        similar_tracks = sp.recommendations(seed_tracks=[id], limit=10)['tracks']
    elif type == "artist":
        similar_tracks = sp.recommendations(seed_artists=[id], limit=10)['tracks']
    
    # Extract track URIs from similar tracks
    track_uris = [track['uri'] for track in similar_tracks]

    # Create a new playlist
    playlist = sp.user_playlist_create(user=username, name=playlist_name, public=False)

    # Add tracks to the playlist
    sp.playlist_add_items(playlist_id=playlist['id'], items=track_uris)

    return playlist

playlist = create_playlist_with_recommendations("track", "6UBjSnyP1O5W5ndJoO9vUk") # Night Moves - Bob Seger
playlist = create_playlist_with_recommendations("artist", "3qBdT7NKSOBogHhGiUVLiV") # Radio Company - country rock

> HTTP Error for POST to https://api.spotify.com/v1/users/9qk7akrruah30sd2qix0x4lmp/playlists with Params: {} returned 403 due to Insufficient client scope
> {
    "name": "SpotifyException",
    "message": "http status: 403, code:-1 - https://api.spotify.com/v1/users/9qk7akrruah30sd2qix0x4lmp/playlists:
 Insufficient client scope, reason: None",
    "stack": "---------------------------------------------------------------------------
HTTPError                                 Traceback (most recent call last)
File ~\\anaconda3\\Lib\\site-packages\\spotipy\\client.py:271, in Spotify._internal_call(self, method, url, payload, params)
    266 response = self._session.request(
    267     method, url, headers=headers, proxies=self.proxies,
    268     timeout=self.requests_timeout, **args
    269 )
--> 271 response.raise_for_status()
    272 results = response.json()

File ~\\anaconda3\\Lib\\site-packages\\requests\\models.py:1021, in Response.raise_for_status(self)
   1020 if http_error_msg:
-> 1021     raise HTTPError(http_error_msg, response=self)

HTTPError: 403 Client Error: Forbidden for url: https://api.spotify.com/v1/users/9qk7akrruah30sd2qix0x4lmp/playlists

During handling of the above exception, another exception occurred:

SpotifyException                          Traceback (most recent call last)
Cell In[10], line 26
     23     return playlist
     25 #playlist = create_playlist_with_recommendations(\"track\", \"6UBjSnyP1O5W5ndJoO9vUk\") # Night Moves - Bob Seger
---> 26 playlist = create_playlist_with_recommendations(\"artist\", \"3qBdT7NKSOBogHhGiUVLiV\") # Radio Company - country rock

Cell In[10], line 18, in create_playlist_with_recommendations(type, id, playlist_name)
     15 track_uris = [track['uri'] for track in similar_tracks]
     17 # Create a new playlist
---> 18 playlist = sp.user_playlist_create(user=username, name=playlist_name, public=False)
     20 # Add tracks to the playlist
     21 sp.playlist_add_items(playlist_id=playlist['id'], items=track_uris)

File ~\\anaconda3\\Lib\\site-packages\\spotipy\\client.py:818, in Spotify.user_playlist_create(self, user, name, public, collaborative, description)
    802 \"\"\" Creates a playlist for a user
    803 
    804     Parameters:
   (...)
    809         - description - the description of the playlist
    810 \"\"\"
    811 data = {
    812     \"name\": name,
    813     \"public\": public,
    814     \"collaborative\": collaborative,
    815     \"description\": description
    816 }
--> 818 return self._post(\"users/%s/playlists\" % (user,), payload=data)

File ~\\anaconda3\\Lib\\site-packages\\spotipy\\client.py:328, in Spotify._post(self, url, args, payload, **kwargs)
    326 if args:
    327     kwargs.update(args)
--> 328 return self._internal_call(\"POST\", url, payload, kwargs)

File ~\\anaconda3\\Lib\\site-packages\\spotipy\\client.py:293, in Spotify._internal_call(self, method, url, payload, params)
    286         reason = None
    288     logger.error(
    289         'HTTP Error for %s to %s with Params: %s returned %s due to %s',
    290         method, url, args.get(\"params\"), response.status_code, msg
    291     )
--> 293     raise SpotifyException(
    294         response.status_code,
    295         -1,
    296         \"%s:\
 %s\" % (response.url, msg),
    297         reason=reason,
    298         headers=response.headers,
    299     )
    300 except requests.exceptions.RetryError as retry_error:
    301     request = retry_error.request

SpotifyException: http status: 403, code:-1 - https://api.spotify.com/v1/users/9qk7akrruah30sd2qix0x4lmp/playlists:
 Insufficient client scope, reason: None"
}

但是这很完美:

def get_favourites(item_type, time_range='short_term', limit=10):
    # Set up Spotify API client with access token
    sp = spotipy.Spotify(auth_manager=SpotifyOAuth(client_id=client_id,
                                                   client_secret=client_secret,
                                                   redirect_uri=redirect_uri,
                                                   scope='user-top-read'))

    # Validate item_type
    if item_type not in ['tracks', 'artists']:
        raise ValueError("Invalid item_type. Must be 'tracks' or 'artists'.")

    # Get the user's top items
    if item_type == 'tracks':
        top_items = sp.current_user_top_tracks(
            time_range=time_range, limit=limit)
        # Extract relevant information from the tracks
        items_info = []
        for item in top_items['items']:
            item_info = {
                'name': item['name'],
                'artist': item['artists'][0]['name'],
                'album': item['album']['name'],
                'popularity': item['popularity'],
                'id': item['id']
            }
            items_info.append(item_info)
    elif item_type == 'artists':
        top_items = sp.current_user_top_artists(
            time_range=time_range, limit=limit)
        # Extract relevant information from the artists
        items_info = []
        for item in top_items['items']:
            item_info = {
                'name': item['name'],
                'id': item['id'],
                'genres': item['genres'],
                'popularity': item['popularity']
            }
            items_info.append(item_info)

    return items_info


# Example usage
top_tracks = get_favourites(item_type='tracks')
for track in top_tracks:
    print(f"Track ID: {track['id']}\nTrack: {track['name']} - Artist: {track['artist']} - Album: {track['album']} - Popularity: {track['popularity']}\n")

top_artists = get_favourites(item_type='artists')
for artist in top_artists:
    print(
        f"Artist ID: {artist['id']}\nArtist: {artist['name']} - Genres: {', '.join(artist['genres'])} - Popularity: {artist['popularity']}\n")

我已经多次重新运行代码来制作播放列表推荐程序,我从谷歌和chatGPT获得了新代码,但无济于事,我尝试在不同的IDE上运行它,在Spotify WebAPI仪表板上创建一个新项目和nada。

有人能解决这个问题吗?我失去了我的中间哈哈

spotify spotipy
1个回答
0
投票

你必须留意似乎不适合你想做的事情的范围。我们实际上可以看到,有效的代码与无效的代码的作用域不同。
由于您正在尝试修改播放列表,因此您应该使用 :

sp = spotipy.Spotify(auth_manager=SpotifyOAuth(client_id=os.getenv('SPOTIFY_CLIENT_ID'),
                                               client_secret=os.getenv('SPOTIFY_CLIENT_SECRET'),
                                               redirect_uri=os.getenv('SPOTIFY_REDIRECT_URI'),
                                               scope='playlist-modify-public'))

关于您尝试创建/修改的播放列表的类型,它可以是公共的或私有的。

您可以查看有关范围的 Spotify 文档,这可能会有所帮助: https://developer.spotify.com/documentation/web-api/concepts/scopes

© www.soinside.com 2019 - 2024. All rights reserved.