Cache errors using Spotify API in Python program

Question:

I am running into a problem with my Python script. The code executes, but after it displays a caching error:

Couldn't read cache at: .cache
Couldn't write token to cache at: .cache
Couldn't read cache at: .cache
Couldn't write token to cache at: .cache
Couldn't read cache at: .cache
Couldn't write token to cache at: .cache
Couldn't read cache at: .cache
Couldn't write token to cache at: .cache
Couldn't read cache at: .cache
Couldn't write token to cache at: .cache

I am using Spotify to return songs in a playlist. Then I’m checking that playlist for bad words to filter out songs that can’t be played for kids.

Here is the code I’m using:

import spotipy
from spotipy.oauth2 import SpotifyClientCredentials

spotify_id = "ABC123"
spotify_secret = "456789"

oldies = "738hgt"
kids = "201hgj"
country = "099sdt"

spotify_playlist = country

import lyricsgenius

genius_token = "123456789&ABCEFGHIJKLMNOPQRSTUVWXYZ"
genius = lyricsgenius.Genius(genius_token)
genius.verbose = False
genius.timeout = 100

word_listing = ["bad", "words", "go", "here"]

credentials = SpotifyClientCredentials(client_id=spotify_id, client_secret=spotify_secret)
validate = spotipy.Spotify(auth_manager=credentials)

songs = []

limit = 100

offset = 0

playlist = validate.playlist_tracks(spotify_playlist, limit=limit, offset=offset)

while True:
    playlist = validate.playlist_tracks(spotify_playlist, limit=limit, offset=offset)

    if not len(playlist['items']):
        break
    for items in playlist['items']:
        info = {'artist': items['track']['artists'][0]['name'], 'title': items['track']['name']}
        songs.append(info)

    offset += limit

print("Checking playlist...")

for song in songs:
    print(f"    Checking "{song['title']}" by: {song['artist']}")
    term = genius.search_song(title=song['title'], artist=song['artist'])

    for words in word_listing:
        try:
            if len(term.lyrics) > 10000:
                break
            if words in term.lyrics.lower():
                print(f"      *Found "{words}" in "{song['title']}" by: {song['artist']}")
                continue
        except AttributeError:
            print(f"        *Unable to find lyrics for: "{song['title']}" by: {song['artist']}")
            break
        except:
            print(f"    *Unable to connect to service, moving on...")

I have replaced all my variable values for this example. I have been told this is an issue with Spotify’s API; it’s just a warning that can be ignored.

I have also been told it’s a permissions issue, where Spotify wants to write to a cache directory and it doesn’t have the right permissions to do so.

I’m really not sure what’s causing this issue. The error appears at the beginning of the script, and then after it shows, the rest of the script runs successfully.

Is there something in one of my arguments or statements that’s causing this?

Asked By: Josh Rodgers

||

Answers:

I think it is a permission problem, to fix that you can create a cache directory then set the appropriate permission, here is how you could do it:

import os

cache_dir = '.cache'
if not os.path.exists(cache_dir):
    os.makedirs(cache_dir)

os.chmod(cache_dir, 0o700)

Just place this script at the begining of your code before you create the SpotifyClientCredentials object.

Answered By: Saxtheowl

Ok,

So, I found a solution!

@Saxtheowl’s code probably works, on Windows.

My mistake. I am using a Mac, so it did not work for me. I am posting my answer here to help others on a Mac 🙂

At the beginning of the file I just added the following:

from pathlib import Path
import os
Path.cwd()
os.chdir('/Users/josh/Desktop/test/temp')
Path.cwd()

So, all of my files are in the "test" directory, then it’s writing it’s cache to the temp folder.

I tried to just use the "test" directory, but still ended up with the cache error…somehow, putting it in a subfolder solves the problem 🙂

My command looks like: sudo python3 /Users/josh/Desktop/test/script.py (you need sudo for permissions or you will also get an error)

Thanks,
Josh

Answered By: Josh Rodgers
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.