[GH-ISSUE #1043] Logging out with Spotipy #622

Closed
opened 2026-02-28 00:00:21 +03:00 by kerem · 3 comments
Owner

Originally created by @mirzoyevaa on GitHub (Nov 23, 2023).
Original GitHub issue: https://github.com/spotipy-dev/spotipy/issues/1043

I'm trying to write an app, that will allow people to login and get access to their playlists.
But I'm having a problem when I'm trying to log out from account of previous user: It simple stays with the same access_token and have access to previous account. How can I fix it?

import spotipy
import os
from spotipy.oauth2 import SpotifyOAuth

username = 'user'
scope = 'playlist-read-collaborative playlist-read-private playlist-modify-public playlist-modify-private'

auth_manager = SpotifyOAuth(client_id = CLIENT_ID',
                            client_secret='CLIENT_SECRET', username=username,
                            redirect_uri='http://google.com/', scope=scope)
sp = spotipy.Spotify(auth_manager=auth_manager)
cache_path = f".cache-{username}"
if os.path.exists(cache_path):
    os.remove(cache_path)

if auth_manager.get_access_token() is not None:
    print(f"User {username} is logged in.")

    user_info = sp.current_user()
    print(f"User ID: {user_info['id']}")
else:
    print(f"User {username} is not logged in.")


def get_playlists():
    user = sp.current_user()
    current_playlists = sp.user_playlists(user['id'])['items']

    playlist_with_items = {}
    for playlist in current_playlists:
        playlist_with_items[playlist['name']] = []
        for pl in sp.playlist_items(playlist['id'])['items']:
            playlist_with_items[playlist['name']].append(
                pl['track']['album']['artists'][0]['name'] + '-' + pl['track']['name'])

    return playlist_with_items


def parser(link: str):
    i = 0
    playlist_id = ''
    while i < len(link):
        if link[i:i + 17] == 'open.spotify.com/':
            i += 17
            if link[i] == 'p':
                i += 9
                while i < len(link) and link[i] != '/':
                    playlist_id += link[i]
                    i += 1
                if playlist_id:
                    return playlist_id
                else:
                    raise ValueError("Playlist ID not found")
            else:
                break
        i += 1
    raise ValueError("Invalid link")


def get_playlist_by_url(pl_id):
    current_playlist = sp.playlist_items(pl_id)
    playlist_with_items = []
    for track in current_playlist['items']:
        playlist_with_items.append(track['track']['album']['artists'][0]['name'] + '-' + track['track']['name'])
    return playlist_with_items


def search_create_add(query: list):
    uris = []
    needed_id = None
    for i in query:
        ur = sp.search(i)['tracks']['items'][0]['uri']
        uris.append(ur)
    print(uris)
    sp.user_playlist_create(user_info['id'], name='New_try')
    for playlist in sp.current_user_playlists()['items']:
        if (playlist['name'] == 'New_try'):
            needed_id = playlist['id']
    sp.playlist_add_items(playlist_id=needed_id, items=uris)
Originally created by @mirzoyevaa on GitHub (Nov 23, 2023). Original GitHub issue: https://github.com/spotipy-dev/spotipy/issues/1043 I'm trying to write an app, that will allow people to login and get access to their playlists. But I'm having a problem when I'm trying to log out from account of previous user: It simple stays with the same access_token and have access to previous account. How can I fix it? ``` import spotipy import os from spotipy.oauth2 import SpotifyOAuth username = 'user' scope = 'playlist-read-collaborative playlist-read-private playlist-modify-public playlist-modify-private' auth_manager = SpotifyOAuth(client_id = CLIENT_ID', client_secret='CLIENT_SECRET', username=username, redirect_uri='http://google.com/', scope=scope) sp = spotipy.Spotify(auth_manager=auth_manager) cache_path = f".cache-{username}" if os.path.exists(cache_path): os.remove(cache_path) if auth_manager.get_access_token() is not None: print(f"User {username} is logged in.") user_info = sp.current_user() print(f"User ID: {user_info['id']}") else: print(f"User {username} is not logged in.") def get_playlists(): user = sp.current_user() current_playlists = sp.user_playlists(user['id'])['items'] playlist_with_items = {} for playlist in current_playlists: playlist_with_items[playlist['name']] = [] for pl in sp.playlist_items(playlist['id'])['items']: playlist_with_items[playlist['name']].append( pl['track']['album']['artists'][0]['name'] + '-' + pl['track']['name']) return playlist_with_items def parser(link: str): i = 0 playlist_id = '' while i < len(link): if link[i:i + 17] == 'open.spotify.com/': i += 17 if link[i] == 'p': i += 9 while i < len(link) and link[i] != '/': playlist_id += link[i] i += 1 if playlist_id: return playlist_id else: raise ValueError("Playlist ID not found") else: break i += 1 raise ValueError("Invalid link") def get_playlist_by_url(pl_id): current_playlist = sp.playlist_items(pl_id) playlist_with_items = [] for track in current_playlist['items']: playlist_with_items.append(track['track']['album']['artists'][0]['name'] + '-' + track['track']['name']) return playlist_with_items def search_create_add(query: list): uris = [] needed_id = None for i in query: ur = sp.search(i)['tracks']['items'][0]['uri'] uris.append(ur) print(uris) sp.user_playlist_create(user_info['id'], name='New_try') for playlist in sp.current_user_playlists()['items']: if (playlist['name'] == 'New_try'): needed_id = playlist['id'] sp.playlist_add_items(playlist_id=needed_id, items=uris) ```
kerem 2026-02-28 00:00:21 +03:00
  • closed this issue
  • added the
    question
    label
Author
Owner

@dieser-niko commented on GitHub (Nov 23, 2023):

I'm kinda busy so I couldn't take a proper look at your code. But you might want to take a look at this example: https://github.com/spotipy-dev/spotipy/blob/master/examples/app.py

<!-- gh-comment-id:1824134526 --> @dieser-niko commented on GitHub (Nov 23, 2023): I'm kinda busy so I couldn't take a proper look at your code. But you might want to take a look at this example: https://github.com/spotipy-dev/spotipy/blob/master/examples/app.py
Author
Owner

@dieser-niko commented on GitHub (May 21, 2024):

Hi there, any updates about your problem so far?

<!-- gh-comment-id:2123448875 --> @dieser-niko commented on GitHub (May 21, 2024): Hi there, any updates about your problem so far?
Author
Owner

@dieser-niko commented on GitHub (Jun 3, 2024):

Closing as there is no activity or reply from the author.

You can reopen the issue if you still need help.

<!-- gh-comment-id:2144536810 --> @dieser-niko commented on GitHub (Jun 3, 2024): Closing as there is no activity or reply from the author. You can reopen the issue if you still need help.
Sign in to join this conversation.
No milestone
No project
No assignees
1 participant
Notifications
Due date
The due date is invalid or out of range. Please use the format "yyyy-mm-dd".

No due date set.

Dependencies

No dependencies set.

Reference
starred/spotipy#622
No description provided.