Riosant
Riosant

Reputation: 344

local variable 'data' referenced before assignment - python

I am getting the error in my code

Request Method: GET
Request URL: http://localhost:8000/emotion/
Django Version: 2.2
Exception Type: UnboundLocalError
Exception Value:
local variable 'data' referenced before assignment
Exception Location: C:\Users\Sant\Desktop\music_demo\music_site\views.py in emotion, line 314
Python Executable: C:\Users\Sant\AppData\Local\Programs\Python\Python37-32\python.exe
Python Version: 3.7.3
Python Path:
['C:\Users\Sant\Desktop\music_demo',

Server time: Sun, 16 Jun 2019 17:27:51 +0000

Code:

def emotion(request):
    from mutagen.id3 import ID3
    from mutagen.mp3 import MP3
    import sys
    import spotipy
    from spotipy.oauth2 import SpotifyClientCredentials

    client_id = '26473c91fefc43eca3a6531e0f062723'
    client_secret = '9d7c8ddb18594838ae5db6ad10b3ddf0'
    title = 'lollypop'
    artist = 'pawan singh'

    client_credentials_manager = SpotifyClientCredentials(client_id=client_id, client_secret=client_secret)
    sp = spotipy.Spotify(client_credentials_manager=client_credentials_manager)
    sp.trace=False
    search_query = title+ ' ' + artist
    result = sp.search(search_query)
    for i in result['tracks']['items']:
        # Find a songh that matches title and artist
        if (i['artists'][0]['name'] == artist) and (i['name'] == title):
            print (i['uri'])
            break
    else:
        try:
            # Just take the first song returned by the search (might be named differently)
            print (result['tracks']['items'][0]['uri'])
            uri = result['tracks']['items'][0]['uri']
            client_credentials_manager = SpotifyClientCredentials(client_id=client_id, client_secret=client_secret)
            sp = spotipy.Spotify(client_credentials_manager=client_credentials_manager)
            sp.trace=False
            features = sp.audio_features(uri)

            print ('Energy:', features[0]['energy'])
            data = {
                "energy" :  features[0]["energy"],
                "valence" : features[0]["valence"],
                "key" : features[0]["key"],
                "link" : features[0]["valence"],
                "danceability" : features[0]["link"],
                "loudness" : features[0]["loudness"],
                "tempo" : features[0]["tempo"],
                "acousticness" : features[0]["acousticness"],
                "liveness" : features[0]["liveness"],
                "instrumentalness" : features[0]["instrumentalness"]
            }

        except:
            # No results for artist and title
            print ("Cannot Find URI")
    # return HttpResponse(features[0]['energy'])
    return render(request, 'music_site/emotion.html', data) # Error is raised because of data dictionary

Upvotes: 0

Views: 1728

Answers (1)

gahooa
gahooa

Reputation: 137312

If an exception happens in the try/except block before the line:

`data = {` 

then data will never be set.

You need to set it to a default value (e.g. None) in the except clause, or before the try statement.

Upvotes: 1

Related Questions