локальная переменная 'data', указанная перед присваиванием - python - PullRequest
0 голосов
/ 16 июня 2019

Я получаю ошибку в своем коде

Способ запроса: GET URL запроса: http://localhost:8000/emotion/ Джанго версия: 2.2 Тип исключения: UnboundLocalError Значение исключения:
локальная переменная «данные», на которую ссылаются до Расположение исключения: C: \ Users \ Sant \ Desktop \ music_demo \ music_site \ views.py в эмоциях, строка 314 Исполняемый файл Python: C: \ Users \ Sant \ AppData \ Local \ Programs \ Python \ Python37-32 \ python.exe Версия Python: 3.7.3 Python Path:
[ 'C: \ Users \ Sant \ Desktop \ music_demo',

Время сервера: вс, 16 июня 2019 17:27:51 + 0000

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_querry = title+ ' ' + artist
    result = sp.search(search_querry)
    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

1 Ответ

1 голос
/ 16 июня 2019

Если в блоке try/except перед строкой происходит исключение:

`data = {` 

, то data никогда не будет установлено.

Вам необходимо установить значение по умолчанию (например, Нет) в предложении except или перед оператором try.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...