简体   繁体   English

使用 python 脚本更新 Flask web 页面

[英]Update Flask web page with python script

Program description: I already have a functioning program that runs on console window, but I'd like to present its output on a locally hosted web page.程序描述:我已经有一个在控制台 window 上运行的功能程序,但我想在本地托管的 web 页面上展示它的 output。 The program consists on getting lyrics for currently playing songs by making requests to Spotify's API.该程序包括通过向 Spotify 的 API 发出请求来获取当前播放歌曲的歌词。 I store the current lyrics in a "lyrics.txt" file.我将当前歌词存储在“lyrics.txt”文件中。

What I want:我想要的是:

Change the web page from the running lyrics program when it detects the song has changed.当检测到歌曲已更改时,从正在运行的歌词程序中更改 web 页面。

[EDIT:] [编辑:]

Is there a way to make the flask page display a variable, that is updated by a python request.post of the lyrics app to the flask url with the updated variable as the data? Is there a way to make the flask page display a variable, that is updated by a python request.post of the lyrics app to the flask url with the updated variable as the data?

What I have:我有的:

I'm using Flask as the framework since its a one local web page.我使用 Flask 作为框架,因为它是一个本地 web 页面。

import os, io
from flask import Flask, render_template

app = Flask(__name__)

@app.route("/")
def test():
    '''reads the current lyrics file and passes it to the web page
    manually reload the page to update lyrics'''
    with io.open('lyrics.txt', 'r') as f:
        HEAD = f.readline().strip("\n")
        BODY = f.read().split('\n')

    lyrics = {"HEAD": HEAD, "BODY": BODY}
    return render_template("home.html", lyrics=lyrics)


if __name__ == "__main__":
    app.run(debug=1)

link to lyrics app github链接到歌词应用程序 github

You would need JavaScript/AJAX on page which periodically sends request for new content and Flask should send current content from file.您需要在页面上定期发送对新内容的请求的JavaScript/AJAX ,并且 Flask 应该从文件中发送当前内容。


In this example I use jQuery.get() to send request to server, and setTimeout() to repeat it periodically.在此示例中,我使用jQuery.get()向服务器发送请求,并使用setTimeout()定期重复它。

Flask sends current time to show different content. Flask发送当前时间以显示不同的内容。

import datetime
from flask import Flask, render_template_string

app = Flask(__name__)

@app.route("/")
def index():
    return render_template_string("""<!DOC html>
<html>
<head>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.8.0.min.js"></script>
<script type="text/javascript">
(function worker() {
  $.get('/data', function(data) {
    $('#time').html(data);    // update page with new data
    setTimeout(worker, 1000); // run `worker()` again after 1000ms (1s)
  });
})();
</script>
<meta charset="utf-8" />
<title>Test</title>
</head>
<body>Date & Time: <span id="time"><span></body>
</html>""")


@app.route('/data')
def data():
    """send current content"""
    return datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')

if __name__ == "__main__":
    app.run(debug=True)

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

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