spotDL / spotify-downloader

Download your Spotify playlists and songs along with album art and metadata (from YouTube if a match is found).
https://spotdl.readthedocs.io/en/latest/
MIT License
17.35k stars 1.6k forks source link

A spotify client has already been initialized #1979

Closed ErfanCyber10 closed 9 months ago

ErfanCyber10 commented 10 months ago

System OS

Linux

Python Version

3.11 (CPython)

Install Source

pip / PyPi

Install version / commit hash

4.2.4

Expected Behavior vs Actual Behavior

I want create Simple web api here is my code :

from spotdl import Spotdl
from flask import Flask, request, jsonify
import json

app = Flask(__name__)

@app.route('/spotifydownloader')  # Make sure the route starts with a '/'
def download():
    url = request.args.get('url', '')  # Get the URL parameter from the request query
    return spotify_download(url)

def spotify_download(url2):
    spotdl = Spotdl(client_id='541f7a', client_secret='8bfad3f4abb')

    songs = spotdl.search([url2])
    song = songs[0]

    dn = spotdl.download(song)

    MusicInfo = {
      "name": song.name,
      "artists": ' -  '.join(song.artists),
      "photo": song.cover_url,
      "date": song.date,
      "filename" : str(dn[1])
    }

    return MusicInfo

if __name__ == '__main__':
    app.run(debug=True)

Its ok and works , but when 2 user request I got this error :

A spotify client has already been initialized

Steps to reproduce - Ensure to include actual links!

.

Traceback

A spotify client has already been initialized

Other details

..............................elpelf

keplerHaloxx commented 10 months ago
def spotify_download(url2):
    spotdl = Spotdl(client_id='541f7a', client_secret='8bfad3f4abb')

Over here you are setting the value of spotdl again every time you download another song. What you should do is make the value once outside of the functions something like this



from spotdl import Spotdl
from flask import Flask, request, jsonify
import json

app = Flask(__name__)

spotdl = Spotdl(client_id='541f7a', client_secret='8bfad3f4abb')

@app.route('/spotifydownloader')  # Make sure the route starts with a '/'
def download():
    url = request.args.get('url', '')  # Get the URL parameter from the request query
    return spotify_download(url)

def spotify_download(url2):
    songs = spotdl.search([url2])
    song = songs[0]

    dn = spotdl.download(song)

    MusicInfo = {
      "name": song.name,
      "artists": ' -  '.join(song.artists),
      "photo": song.cover_url,
      "date": song.date,
      "filename" : str(dn[1])
    }

    return MusicInfo

if __name__ == '__main__':
    app.run(debug=True)
xnetcat commented 9 months ago

@keplerHaloxx is correct, spotdl class should only be initialized once. if you want to change something afterwards take a look at the code in the entry point/web code and use downloader instead