简体   繁体   English

Flask 返回渲染模板不工作(Spotify API)

[英]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.我正在尝试创建一个网页来显示用户当前播放的曲目详细信息和自动更新,但 html 页面在曲目更改时不会刷新变量,即使 python 程序运行完美且没有抛出错误。

Python Code: Python 代码:

@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 代码:

<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.我希望 HTML 页面刷新并显示新变量。 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.你可以使用一个小的 JavaScript 脚本,它运行在客户端,在你定义的关键时刻刷新整个页面,这里是音乐的结束。

I recommend you to refresh only some elements of the page via JavaScript and APIs.我建议您通过 JavaScript 和 API 仅刷新页面的某些元素。 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.当客户端播放完音乐后,它会通过 API 警告服务器。服务器会向他发送新歌曲。

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".然后,将 JavaScript 脚本放在一个文件夹中,这里是“static”。 Remember to specify this in the Flask init.请记住在 Flask 初始化中指定它。

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

And call the JavaScript in your HTML page并在您的 HTML 页面中拨打 JavaScript

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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