我无法在我的motion.html

时间:2019-06-16 13:41:36

标签: python django

我是python的新手,我正在使用spotify api检测音乐的情感,但是当我将字典值传递给html时,它什么也不会打印。而我可以在命令行中打印

当我写{{energy}}时 当我访问localhost:8000 // emotion

时,它什么也不打印

这是我在views.py中的功能

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

    client_id = '**********************'
    client_secret = '*****************************'
    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)

            data = {
                'energy' : features[0]['energy'],
                'key' : features[0]['key'],
                'valence': features[0]['valence'],
                'danceability': features[0]['danceability'],
                'loundness' : features[0]['loudness'],
                'tempo' : round(features[0]['tempo']),
                'acousticness' : features[0]['acousticness'],
                'liveness' : features[0]['liveness'],
                'instrumentalness' : features[0]['instrumentalness'],
            }

            print(features[0]['energy'])  # Prints successfully 0.862

        except:
            data = { 'error' : 'NO SONGS FOUND' }
    return render(request, 'emotion_view.html', data)

这是我在模板中的motion_view.html

{{ energy }}

在motion_view.html中,它什么也不打印,这是什么问题

1 个答案:

答案 0 :(得分:0)

在数据字典中传递{{energy}}而不是{{error}}时,将emotion_view.html中的'error'更改为'energy'