首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >用python脚本更新烧瓶网页

用python脚本更新烧瓶网页
EN

Stack Overflow用户
提问于 2019-11-22 15:02:41
回答 1查看 2.6K关注 0票数 4

程序描述:我已经有了一个运行在控制台窗口上的程序,但是我想把它的输出显示在本地托管的网页上。这个程序包括通过请求Spotify的API来获得当前播放歌曲的歌词。我将当前的歌词存储在一个"lyrics.txt“文件中。

我想要的:

从正在运行的歌词程序更改网页时,它检测到歌曲已经改变。

编辑:

有没有一种方法可以让烧瓶页面显示一个变量,这个变量由歌词应用程序的python request.post更新到烧瓶url,并以更新的变量作为数据?

我拥有的:

我使用的框架作为框架,因为它是一个本地网页。

代码语言:javascript
复制
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)

链接到歌词应用程序github

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-11-22 16:42:25

您需要页面上的JavaScript/AJAX,它定期发送新内容的请求,而Flask应该从文件中发送当前的内容。

在本例中,我使用jQuery.get()向服务器发送请求,setTimeout()定期重复该请求。

Flask发送当前时间来显示不同的内容。

代码语言:javascript
复制
import datetime
from flask import Flask, render_template_string

app = Flask(__name__)

@app.route("/")
def index():
    return render_template_string("""<!DOCTYPE html>
<html>

<head>
<meta charset="utf-8" />
<title>Test</title>

<script type="text/javascript" src="http://code.jquery.com/jquery-1.8.0.min.js"></script>

<script type="text/javascript">
function updater() {
  $.get('/data', function(data) {
    $('#time').html(data);  // update page with new data
  });
};

setInterval(updater, 1000);  // run `updater()` every 1000ms (1s)
</script>

</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)

编辑:

同样使用没有外部库的标准fetch()

代码必须在<span>之后

代码语言:javascript
复制
import datetime
from flask import Flask, render_template_string

app = Flask(__name__)

@app.route("/")
def index():
    return render_template_string("""<!DOCTYPE html>
<html>

<head>
<meta charset="utf-8" />
<title>Test</title>
</head>

<body>

Date & Time: <span id="time"><span>

<script type="text/javascript">
var time_span = document.getElementById("time");

function updater() {
  fetch('/data')
  .then(response => response.text())
  .then(text => (time_span.innerHTML = text));  // update page with new data
}

setInterval(updater, 1000);  // run `updater()` every 1000ms (1s)
</script>

</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)
票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/58996870

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档