简体   繁体   中英

Flask Return Render Template Not Working (Spotify API)

I'm trying to create a webpage which display's the user's current playing track details and auto updates but the html page does not refresh the variables when the track changes even though the python program runs flawlessly without throwing errors.

Python Code:

@app.route('/vintage')
def vintage():

    cache_handler = spotipy.cache_handler.FlaskSessionCacheHandler(session)
    auth_manager = spotipy.oauth2.SpotifyOAuth(cache_handler=cache_handler, show_dialog=False, scope='user-read-currently-playing')
    if not auth_manager.validate_token(cache_handler.get_cached_token()):
        return redirect('/')
    spotify = spotipy.Spotify(auth_manager=auth_manager)

    try:
        track = spotify.current_user_playing_track()["item"]["name"]
        global trackg
        trackg = track
        artist = spotify.current_user_playing_track()["item"]["artists"][0]["name"]
        image = spotify.current_user_playing_track()["item"]["album"]["images"][0]["url"]
            
    except TypeError:
        track = "Your Player Is Idle"
        artist = "Visuafy Will Refresh Automatically"
        image = url_for('static', filename='idle.jpeg')

    @copy_current_request_context
    def scan():
        while True:
            new_track = spotify.current_user_playing_track()["item"]["name"]
            if (new_track != trackg):
                return render_template('vintage.html', track=new_track)
                    
    
    v = threading.Thread(target=scan)
    v.start()

    return render_template('vintage.html', track = track, artist = artist, image=image, reload=False)

HTML Code:

<html>
<body>
    <div class="d-flex flex-column justify-content-center w-100 h-100">

        <div class="d-flex flex-column justify-content-center align-items-center">
         
            <div class="center">
                    <center>
                        <img src="{{image}}" height="300" width="300" style="border-radius: 5%;">
                        <h1>{{track}}</h1>
                        <h3>{{artist}}</h3>
                   
                    </center>
</body>
</html>

I expected the HTML page to refresh and display the new variable. I even tried redirecting but it didn't work.

The server cannot tell the client to refresh its page. It is the client that must refresh itself.

You can use a small JavaScript script, which runs on the client side, to refresh the whole page at key moments that you define, here is the end of a music.

I recommend you to refresh only some elements of the page via JavaScript and APIs. This is less resource intensive.

When the client has finished the music, it warns the server, via the API. And the server sends him the new song.

from flask import request

@app.route('/vintage', methods=("GET", "POST"))
def vintage():
    if request.method == "POST":
        """next song call with API"""
        return """new data"""
    else:
        """load page"""

Then, you put your JavaScript script in a folder, here "static". Remember to specify this in the Flask init.

app = Flask(__name__, template_folder="templates", static_folder="static")

And call the JavaScript in your HTML page

<script src="{{ url_for('static', filename='myscript.js') }}"></script>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM