赋值之前引用的局部变量“数据”-python

时间:2019-06-16 17:35:09

标签: python django

我的代码中出现错误

请求方法:GET 要求网址:http://localhost:8000/emotion/ Django版本: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路径:
['C:\ Users \ Sant \ Desktop \ music_demo',

服务器时间:2019年6月16日,星期日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 个答案:

答案 0 :(得分:1)

如果在行之前的try/except块中发生异常:

`data = {` 

然后将永远不会设置data

您需要在except子句中或try语句之前将其设置为默认值(例如,无)。